Skip to content

Commit 4600d98

Browse files
authored
Warn when using a non-empty spec.Servers (#883)
It's a fairly common mistake when using the OpenAPI request validation filter from kin-openapi to receive `no matching operation was found` errors if using the `servers` directive in your OpenAPI specification. This is a valid usescase, but you may not always want to be enforcing the validation that the `Host` header matches one of the `servers` mentioned in your specification. This makes it clearer to operators that there may be a configuration issue here, as a way to avoid as many folks falling into the same trap that many have before. This also provides an option to silence the warning, as logging out can be annoying and costly. Closes #882.
1 parent cd39124 commit 4600d98

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

oapi_validate.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"context"
1919
"errors"
2020
"fmt"
21+
"log"
2122
"net/http"
2223
"os"
2324
"strings"
@@ -70,10 +71,16 @@ type Options struct {
7071
ParamDecoder openapi3filter.ContentParameterDecoder
7172
UserData interface{}
7273
MultiErrorHandler MultiErrorHandler
74+
// SilenceServersWarning allows silencing a warning for https://github.com/deepmap/oapi-codegen/issues/882 that reports when an OpenAPI spec has `spec.Servers != nil`
75+
SilenceServersWarning bool
7376
}
7477

7578
// OapiRequestValidatorWithOptions creates a validator from a swagger object, with validation options
7679
func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) gin.HandlerFunc {
80+
if swagger.Servers != nil && (options == nil || options.SilenceServersWarning) {
81+
log.Println("WARN: OapiRequestValidatorWithOptions called with an OpenAPI spec that has `Servers` set. This may lead to an HTTP 400 with `no matching operation was found` when sending a valid request, as the validator performs `Host` header validation. If you're expecting `Host` header validation, you can silence this warning by setting `Options.SilenceServersWarning = true`. See https://github.com/deepmap/oapi-codegen/issues/882 for more information.")
82+
}
83+
7784
router, err := gorillamux.NewRouter(swagger)
7885
if err != nil {
7986
panic(err)

0 commit comments

Comments
 (0)