Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions openapi3filter/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type Validator struct {
errFunc ErrFunc
logFunc LogFunc
strict bool
options Options
}

// ErrFunc handles errors that may occur during validation.
Expand Down Expand Up @@ -106,6 +107,13 @@ func Strict(strict bool) ValidatorOption {
}
}

// ValidationOptions sets request/response validation options on the validator.
func ValidationOptions(options Options) ValidatorOption {
return func(v *Validator) {
v.options = options
}
}

// Middleware returns an http.Handler which wraps the given handler with
// request and response validation.
func (v *Validator) Middleware(h http.Handler) http.Handler {
Expand All @@ -120,6 +128,7 @@ func (v *Validator) Middleware(h http.Handler) http.Handler {
Request: r,
PathParams: pathParams,
Route: route,
Options: &v.options,
}
if err = ValidateRequest(r.Context(), requestValidationInput); err != nil {
v.logFunc("invalid request", err)
Expand All @@ -141,6 +150,7 @@ func (v *Validator) Middleware(h http.Handler) http.Handler {
Status: wr.statusCode(),
Header: wr.Header(),
Body: ioutil.NopCloser(bytes.NewBuffer(wr.bodyContents())),
Options: &v.options,
}); err != nil {
v.logFunc("invalid response", err)
if v.strict {
Expand Down
21 changes: 21 additions & 0 deletions openapi3filter/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,27 @@ func TestValidator(t *testing.T) {
body: `{"id": "42", "contents": {"name": "foo", "expected": 9, "actual": 10}, "extra": true}`,
},
strict: false,
}, {
name: "POST response status code not in spec (return 200, spec only has 201)",
handler: validatorTestHandler{
postBody: `{"id": "42", "contents": {"name": "foo", "expected": 9, "actual": 10}, "extra": true}`,
errStatusCode: 200,
errBody: `{"id": "42", "contents": {"name": "foo", "expected": 9, "actual": 10}, "extra": true}`,
}.withDefaults(),
options: []openapi3filter.ValidatorOption{openapi3filter.ValidationOptions(openapi3filter.Options{
IncludeResponseStatus: true,
})},
request: testRequest{
method: "POST",
path: "/test?version=1",
body: `{"name": "foo", "expected": 9, "actual": 10}`,
contentType: "application/json",
},
response: testResponse{
statusCode: 200,
body: `{"id": "42", "contents": {"name": "foo", "expected": 9, "actual": 10}, "extra": true}`,
},
strict: false,
}}
for i, test := range tests {
t.Logf("test#%d: %s", i, test.name)
Expand Down