-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.go
67 lines (57 loc) · 1.61 KB
/
schema.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
package main
import (
"context"
"fmt"
"net/http"
"net/url"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers/gorillamux"
)
func loadSchema(path string) (schema *openapi3.T, err error) {
loader := openapi3.NewLoader()
schemaURI, err := url.Parse(path)
if err != nil {
schema, err = loader.LoadFromFile(path)
} else {
schema, err = loader.LoadFromURI(schemaURI)
}
return schema, err
}
func (a *app) getSchemaRouter() http.HandlerFunc {
schema, err := loadSchema(a.schemaPath)
if err != nil {
panic(fmt.Sprintf("Failed to load schema: %+v", err))
}
if err := schema.Validate(context.Background()); err != nil {
panic(fmt.Sprintf("Schema validation failed: %+v", err))
}
router, err := gorillamux.NewRouter(schema)
if err != nil {
panic(fmt.Sprintf("Failed to create router: %+v", err))
}
return func(w http.ResponseWriter, r *http.Request) {
route, params, err := router.FindRoute(r)
if err != nil {
resp := fmt.Sprintf("Failed to find route: %+v\n", err)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(resp))
return
}
requestValidationInput := &openapi3filter.RequestValidationInput{
Request: r,
PathParams: params,
Route: route,
}
if err := openapi3filter.ValidateRequest(r.Context(), requestValidationInput); err != nil {
resp := fmt.Sprintf("Request validation failed: %+v\n", err)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(resp))
return
}
resp := fmt.Sprintf(`Route: %s %s
Params: %+v
`, route.Method, route.Path, params)
w.Write([]byte(resp))
}
}