-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
openapi3.go
87 lines (77 loc) · 1.75 KB
/
openapi3.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
package httpstub
import (
"bytes"
"errors"
"io"
"net/http"
)
var _ http.ResponseWriter = (*recorder)(nil)
type recorder struct {
rw http.ResponseWriter
statusCode int
body *bytes.Buffer
}
func newRecorder(rw http.ResponseWriter) *recorder {
return &recorder{
rw: rw,
body: bytes.NewBuffer(nil),
}
}
func (r *recorder) Header() http.Header {
return r.rw.Header()
}
func (r *recorder) Write(b []byte) (int, error) {
if n, err := r.body.Write(b); err != nil {
return n, err
}
return r.rw.Write(b)
}
func (r *recorder) WriteHeader(statusCode int) {
r.statusCode = statusCode
r.rw.WriteHeader(statusCode)
}
func (r *recorder) toResponse() *http.Response {
return &http.Response{
Status: http.StatusText(r.statusCode),
StatusCode: r.statusCode,
Body: io.NopCloser(r.body),
Header: r.rw.Header().Clone(),
}
}
func (rt *Router) setOpenApi3Vaildator() error {
rt.t.Helper()
rt.mu.Lock()
defer rt.mu.Unlock()
if rt.openAPI3Doc == nil {
return nil
}
mw := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
v := *rt.openAPI3Validator
if !rt.skipValidateRequest {
_, errs := v.ValidateHttpRequest(r)
if len(errs) > 0 {
var err error
for _, e := range errs {
err = errors.Join(err, e)
}
rt.t.Errorf("failed to validate response: %v", err)
}
}
rec := newRecorder(w)
next.ServeHTTP(rec, r)
if !rt.skipValidateResponse {
_, errs := v.ValidateHttpResponse(r, rec.toResponse())
if len(errs) > 0 {
var err error
for _, e := range errs {
err = errors.Join(err, e)
}
rt.t.Errorf("failed to validate response: %v", err)
}
}
}
}
rt.middlewares = append(rt.middlewares, mw)
return nil
}