Skip to content

Commit fad9c45

Browse files
committed
add exempt routes
1 parent 894d716 commit fad9c45

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

openapi.go

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,20 @@ import (
1212
"github.com/getkin/kin-openapi/routers"
1313
"github.com/getkin/kin-openapi/routers/gorillamux"
1414
"github.com/labstack/echo/v4"
15+
"github.com/labstack/echo/v4/middleware"
1516
)
1617

1718
type Config struct {
18-
Schema string
19-
ContextKey string
19+
// Skipper defines a function to skip middleware.
20+
Skipper middleware.Skipper
21+
22+
Schema string
23+
ContextKey string
24+
ExemptRoutes map[string][]string
2025
}
2126

2227
var DefaultConfig = Config{
28+
Skipper: middleware.DefaultSkipper,
2329
ContextKey: "validator",
2430
}
2531

@@ -30,8 +36,24 @@ func OpenAPI(file string) echo.MiddlewareFunc {
3036
}
3137

3238
func OpenAPIWithConfig(config Config) echo.MiddlewareFunc {
39+
if config.Skipper == nil {
40+
config.Skipper = DefaultConfig.Skipper
41+
}
42+
43+
if config.ContextKey == "" {
44+
config.ContextKey = DefaultConfig.ContextKey
45+
}
46+
3347
return func(next echo.HandlerFunc) echo.HandlerFunc {
3448
return func(c echo.Context) error {
49+
if config.Skipper(c) {
50+
return next(c)
51+
}
52+
53+
if check(c.Path(), c.Request().Method, config.ExemptRoutes) {
54+
return next(c)
55+
}
56+
3557
ctx := context.Background()
3658
loader := &openapi3.Loader{Context: ctx, IsExternalRefsAllowed: true}
3759
schema, err := loader.LoadFromFile(config.Schema)
@@ -154,6 +176,19 @@ func convertError(me openapi3.MultiError) map[string][]string {
154176
return issues
155177
}
156178

179+
func check(path string, method string, m map[string][]string) bool {
180+
for k, v := range m {
181+
if k == path {
182+
for _, i := range v {
183+
if method == i {
184+
return true
185+
}
186+
}
187+
}
188+
}
189+
return false
190+
}
191+
157192
type ValidationError struct {
158193
echo.HTTPError
159194
Errors []string `json:"errors,omitempty"`

0 commit comments

Comments
 (0)