-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
108 lines (94 loc) · 2.8 KB
/
validate.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
105
106
107
108
package httplib
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"github.com/xeipuuv/gojsonschema"
)
type ValidationResult struct {
Valid bool `json:"valid"`
Errors interface{} `json:"errors"`
ObjectIndex *int `json:"item,omitempty"`
}
func ErrorValidationResult(vr *gojsonschema.Result) ValidationResult {
var errors []gojsonschema.ErrorDetails
for _, e := range vr.Errors() {
errors = append(errors, e.Details())
}
return ValidationResult{Valid: vr.Valid(), Errors: errors}
}
type nopCloser struct {
io.Reader
}
func (nopCloser) Close() error { return nil }
type InvalidJSONError struct {
gojsonschema.ResultErrorFields
}
// ValidateJSONSchema returns a http middleware that validates the supplied
// JSON schema. Will panic if the schema file can't be found and/or is invalid
// The validator supports streaming JSON, and will buffer all data to check its
// validity. If any of the streamed objects is invalid, subsequent handlers will
// not be called.
func ValidateJSONSchema(path string) func(http.Handler) http.Handler {
schemaLoader := gojsonschema.NewReferenceLoader("file://" + path)
schema, err := gojsonschema.NewSchema(schemaLoader)
if err != nil {
panic(err)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read body: "+err.Error(), http.StatusBadRequest)
return
}
bufReader := bytes.NewReader(buf)
dec := json.NewDecoder(bufReader)
var validationErrorCount int
var validationResults []ValidationResult
for {
var obj interface{}
if err := dec.Decode(&obj); err == io.EOF {
break
} else if err != nil {
validationResults = append(validationResults,
ValidationResult{
Valid: false,
Errors: []string{"Invalid JSON: " + err.Error()},
})
validationErrorCount++
// When reach an invalid JSON, we can't proceed since we can't
// segment subsequent objects correctly
break
}
objLoader := gojsonschema.NewGoLoader(obj)
validationResult, err := schema.Validate(objLoader)
if err != nil {
http.Error(w, "Failed to validate: "+err.Error(), http.StatusInternalServerError)
return
}
if validationResult.Valid() != true {
validationErrorCount++
}
validationResults = append(validationResults,
ErrorValidationResult(validationResult),
)
}
if validationErrorCount > 0 {
w.WriteHeader(http.StatusBadRequest)
for i := range validationResults {
vr := validationResults[i]
vr.ObjectIndex = &i
o, _ := json.Marshal(vr)
w.Write(o)
w.Write([]byte("\n"))
}
return
}
r.Body = nopCloser{bytes.NewReader(buf)}
next.ServeHTTP(w, r)
})
}
}