-
Notifications
You must be signed in to change notification settings - Fork 0
/
validators.go
74 lines (63 loc) · 1.75 KB
/
validators.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
package lib
import (
"bytes"
"github.com/cubahno/connexions/openapi"
validator "github.com/pb33f/libopenapi-validator"
"github.com/pb33f/libopenapi-validator/errors"
"io"
"net/http"
)
type Validator struct {
innerValidator validator.Validator
}
// NewValidator creates a new Validator using the libopenapi-validator library
func NewValidator(doc openapi.Document) openapi.Validator {
d, ok := doc.(*V3Document)
if !ok {
return nil
}
v := validator.NewValidatorFromV3Model(&d.Model)
return &Validator{
innerValidator: v,
}
}
// ValidateRequest validates a GeneratedRequest against the OpenAPI document.
// Implements Validator interface.
func (v *Validator) ValidateRequest(req *openapi.GeneratedRequest) []error {
ok, valErrs := v.innerValidator.ValidateHttpRequest(req.Request)
if ok {
return nil
}
return v.getErrors(valErrs)
}
// ValidateResponse validates a response against the OpenAPI document.
// Implements Validator interface.
func (v *Validator) ValidateResponse(res *openapi.GeneratedResponse) []error {
readCloser := io.NopCloser(bytes.NewReader(res.Content))
httpResponse := &http.Response{
StatusCode: res.StatusCode,
Header: res.Headers,
Body: readCloser,
Request: res.Request,
ContentLength: -1,
}
ok, valErrs := v.innerValidator.ValidateHttpResponse(res.Request, httpResponse)
if ok {
return nil
}
return v.getErrors(valErrs)
}
// getErrors converts the errors.ValidationError to []error
func (v *Validator) getErrors(src []*errors.ValidationError) []error {
var res []error
for _, err := range src {
if len(err.SchemaValidationErrors) > 0 {
for _, schemaErr := range err.SchemaValidationErrors {
res = append(res, schemaErr)
}
} else {
res = append(res, err)
}
}
return res
}