-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
104 lines (86 loc) · 2.54 KB
/
validator.go
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
101
102
103
104
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
)
// NuJSONStruct response
type NuJSONStruct 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
}
// Process only one request to validator at a time
validatorMutex.Lock()
defer validatorMutex.Unlock()
req, err := http.NewRequest("POST", htmlValidator, body)
if err != nil {
validatorMutex.Unlock()
log.Fatal(err)
}
req.Header.Set("User-Agent", "Web-validator")
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 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 := NuJSONStruct{}
jsonErr := json.Unmarshal(data, &response)
if jsonErr != nil {
errorsProcessed++
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++
output.ValidationErrors = append(output.ValidationErrors, msg)
}
}
return output
}