-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.go
More file actions
100 lines (83 loc) · 2.42 KB
/
validator.go
File metadata and controls
100 lines (83 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
)
// nuJSON response
type nuJSON struct {
Messages []validationError `json:"messages"`
Source struct {
Type string `json:"type"`
Encoding string `json:"encoding"`
Code string `json:"code"`
} `json:"source"`
Language string `json:"language"`
}
// validationError struct
type validationError struct {
Type string `json:"type"`
LastLine int `json:"lastLine"`
LastColumn int `json:"lastColumn"`
FirstColumn int `json:"firstColumn"`
Message string `json:"message"`
Extract string `json:"extract"`
HiliteStart int `json:"hiliteStart"`
HiliteLength int `json:"hiliteLength"`
}
// Validate will validate HTML & CSS with Nu Validator
func validate(output result, body io.Reader, contentType string) result {
if !strings.Contains(contentType, "text/html") && !strings.Contains(contentType, "text/css") {
return output
}
if !validateHTML && strings.Contains(contentType, "text/html") {
return output
}
if !validateCSS && strings.Contains(contentType, "text/css") {
return output
}
validatorWait()
req, err := http.NewRequest("POST", htmlValidator, body)
if err != nil {
log.Fatal(err)
}
req.Header.Set("User-Agent", userAgent)
if output.Type != "" {
req.Header.Set("Content-Type", contentType)
} else {
req.Header.Set("Content-Type", "text/html; charset=utf-8")
}
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
output.Errors = append(output.Errors, fmt.Sprintf("Validator: %s", err))
return output
}
defer func() { _ = res.Body.Close() }()
data, err := io.ReadAll(res.Body)
if err != nil {
output.Errors = append(output.Errors, fmt.Sprintf("Validator: %s", err))
return output
}
if res.StatusCode != 200 {
output.Errors = append(output.Errors, fmt.Sprintf("Validator: %s returned a %d (%s) response", htmlValidator, res.StatusCode, http.StatusText(res.StatusCode)))
return output
}
response := nuJSON{}
jsonErr := json.Unmarshal(data, &response)
if jsonErr != nil {
errorsProcessed.Add(1)
output.Errors = append(output.Errors, fmt.Sprintf("Error parsing response from %s: %s", htmlValidator, string(data)))
return output
}
for _, msg := range response.Messages {
if msg.Type == "error" || (showWarnings && msg.Type == "info") {
errorsProcessed.Add(1)
output.ValidationErrors = append(output.ValidationErrors, msg)
}
}
return output
}