Skip to content

Commit

Permalink
Expose request/response validation options in the middleware Validator (
Browse files Browse the repository at this point in the history
  • Loading branch information
sorintm authored Sep 21, 2022
1 parent d12860c commit 6610338
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
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

0 comments on commit 6610338

Please sign in to comment.