-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator_schema.go
78 lines (62 loc) · 1.41 KB
/
validator_schema.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
package jsonapi
import (
"bytes"
"github.com/xeipuuv/gojsonschema"
"io"
"net/http"
)
func WithSchema(schema io.Reader) OptsFn {
return func(h *JsonHandler) {
if schema == nil {
return
}
b, err := io.ReadAll(schema)
if err != nil {
panic(err)
}
h.RequestValidator = &jsonSchemaValidator{
loader: gojsonschema.NewBytesLoader(b),
}
}
}
// jsonSchemaValidator validates a request body using json testdata
// It uses the "github.com/xeipuuv/gojsonschema" library to validate
type jsonSchemaValidator struct {
loader gojsonschema.JSONLoader
}
func (v *jsonSchemaValidator) Validate(req *http.Request) ([]*ErrorItem, error) {
defer func(c io.Closer) {
_ = c.Close()
}(req.Body)
b, err := io.ReadAll(req.Body)
if err != nil {
return nil, ErrValidation
}
loader := gojsonschema.NewBytesLoader(b)
buff := bytes.NewBuffer(b)
// We change the body to the buffer
req.Body = io.NopCloser(buff)
result, err := gojsonschema.Validate(v.loader, loader)
if err == io.EOF {
return nil, ErrEmptyBody
}
if err != nil {
return nil, &apiError{
code: 400,
msg: "Error while validating the request",
prev: err,
}
}
if result.Valid() {
return nil, nil
}
errors := make([]*ErrorItem, 0, len(result.Errors()))
for _, res := range result.Errors() {
errors = append(errors, &ErrorItem{
Field: res.Field(),
Value: res.Value(),
Msg: res.Description(),
})
}
return errors, nil
}