-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
162 lines (135 loc) · 4.03 KB
/
handler.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package openapi
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sort"
"strings"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/labstack/echo/v4"
)
const (
ApplicationJSON = echo.MIMEApplicationJSON
)
type Handler struct {
Config HandlerConfig
}
type HandlerConfig struct {
// ContentType sets the Content-Type header of the response.
// Optional. Defaults to "application/json".
ContentType string
// ValidatorKey defines the key that will be used to read the
// *openapi3filter.RequestValidationInput from the echo.Context
// set by the middleware.
// Optional. Defaults to "validator".
ValidatorKey string
// ExcludeRequestBody makes Validate skips request body validation.
// Optional. Defaults to false.
ExcludeRequestBody bool
// ExcludeResponseBody makes Validate skips response body validation.
// Optional. Defaults to false.
ExcludeResponseBody bool
// IncludeResponseStatus so ValidateResponse fails on response
// statuses not defined in the OpenAPI spec.
// Optional. Defaults to true.
IncludeResponseStatus bool
}
var DefaultHandlerConfig = HandlerConfig{
ContentType: ApplicationJSON,
ValidatorKey: "validator",
ExcludeRequestBody: false,
ExcludeResponseBody: false,
IncludeResponseStatus: true,
}
func NewHandler() *Handler {
c := DefaultHandlerConfig
return NewHandlerWithConfig(c)
}
func NewHandlerWithConfig(config HandlerConfig) *Handler {
if config.ContentType == "" {
config.ContentType = DefaultHandlerConfig.ContentType
}
if config.ValidatorKey == "" {
config.ValidatorKey = DefaultHandlerConfig.ValidatorKey
}
return &Handler{Config: config}
}
func (h *Handler) Validate(c echo.Context, code int, v any) error {
return h.validate(c, code, h.Config.ContentType, v)
}
func (h *Handler) ValidateWithContentType(c echo.Context, code int, contentType string, v any) error {
return h.validate(c, code, contentType, v)
}
func (h *Handler) validate(c echo.Context, code int, contentType string, v any) error {
// there's nothing to validate so just return
if code == http.StatusNoContent {
return c.NoContent(code)
}
c.Response().Status = code
input, ok := c.Get(h.Config.ValidatorKey).(*openapi3filter.RequestValidationInput)
if !ok {
return fmt.Errorf("validator key is wrong type")
}
var (
b []byte
err error
)
if strings.HasPrefix(contentType, ApplicationJSON) {
c.Response().Header().Add("Content-Type", contentType)
b, err = json.Marshal(v)
} else {
c.Response().Header().Add("Content-Type", echo.MIMETextPlain)
switch t := v.(type) {
case string:
b = []byte(v.(string))
case []byte:
b = v.([]byte)
default:
return fmt.Errorf("type %s not supported", t)
}
}
if err != nil {
return fmt.Errorf("failed marshaling response: %v", err)
}
responseValidationInput := &openapi3filter.ResponseValidationInput{
RequestValidationInput: input,
Status: c.Response().Status,
Header: c.Response().Header(),
Options: &openapi3filter.Options{
ExcludeRequestBody: h.Config.ExcludeRequestBody,
ExcludeResponseBody: h.Config.ExcludeResponseBody,
IncludeResponseStatus: h.Config.IncludeResponseStatus,
MultiError: true,
},
}
responseValidationInput.SetBodyBytes(b)
ctx := context.Background()
err = openapi3filter.ValidateResponse(ctx, responseValidationInput)
if err != nil {
switch err := err.(type) {
case nil:
case *openapi3filter.ResponseError:
if me, ok := err.Err.(openapi3.MultiError); ok {
issues := convertError(me)
names := make([]string, 0, len(issues))
for k := range issues {
names = append(names, k)
}
sort.Strings(names)
var errors []string
for _, k := range names {
msgs := issues[k]
for _, msg := range msgs {
errors = append(errors, msg)
}
}
return fmt.Errorf("failed validating response: %s", strings.Join(errors, "; "))
}
default:
return fmt.Errorf("failed validating response: %v", err)
}
}
return c.Blob(code, h.Config.ContentType, b)
}