-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.go
More file actions
283 lines (250 loc) · 7.43 KB
/
router.go
File metadata and controls
283 lines (250 loc) · 7.43 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package openapirouter
import (
"context"
"errors"
"fmt"
"net/http"
"regexp"
"slices"
"strings"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/labstack/echo/v5"
validator "github.com/responsibleapi/echo-middleware"
)
const (
KeyOperation = "openApiOperation"
KeyValidatedRequest = "openApiValidatedRequest"
)
var pathParamRE = regexp.MustCompile(`\{([^{}]+)\}`)
type RouterBuilder struct {
spec *openapi3.T
rootMiddlewares []echo.MiddlewareFunc
routes map[string]*OpenAPIRoute
orderedRoutes []*OpenAPIRoute
securityHandlers map[string][]SecurityHandler
validationOptions validator.Options
}
type routeRegistrar interface {
AddRoute(route echo.Route) (echo.RouteInfo, error)
}
func NewRouterBuilder(spec *openapi3.T, options validator.Options) (*RouterBuilder, error) {
if spec == nil {
return nil, errors.New("openapi spec cannot be nil")
}
if spec.Paths == nil {
return nil, errors.New("openapi spec paths cannot be nil")
}
if err := spec.Validate(context.Background()); err != nil {
return nil, fmt.Errorf("invalid openapi spec: %w", err)
}
builder := &RouterBuilder{
spec: spec,
routes: make(map[string]*OpenAPIRoute),
securityHandlers: make(map[string][]SecurityHandler),
validationOptions: options,
}
if err := builder.collectRoutes(); err != nil {
return nil, err
}
return builder, nil
}
func LoadFromFile(path string, options validator.Options) (*RouterBuilder, error) {
spec, err := openapi3.NewLoader().LoadFromFile(path)
if err != nil {
return nil, err
}
return NewRouterBuilder(spec, options)
}
func (builder *RouterBuilder) GetRoute(operationID string) *OpenAPIRoute {
return builder.route(operationID, "GetRoute")
}
func (builder *RouterBuilder) AddRoute(
operationID string,
handler echo.HandlerFunc,
middleware ...echo.MiddlewareFunc,
) *OpenAPIRoute {
route := builder.route(operationID, "AddRoute")
if handler == nil {
panic(fmt.Sprintf("openapirouter: AddRoute(%q): handler cannot be nil", operationID))
}
route.Use(middleware...)
route.AddHandler(handler)
return route
}
func (builder *RouterBuilder) Routes() []*OpenAPIRoute {
return slices.Clone(builder.orderedRoutes)
}
func (builder *RouterBuilder) RootHandler(middleware echo.MiddlewareFunc) *RouterBuilder {
if middleware != nil {
builder.rootMiddlewares = append(builder.rootMiddlewares, middleware)
}
return builder
}
func (builder *RouterBuilder) Security(name string, handler SecurityHandler) *RouterBuilder {
if handler == nil {
panic(fmt.Sprintf("openapirouter: Security(%q): handler cannot be nil", name))
}
if _, err := builder.securityScheme(name); err != nil {
panic(fmt.Sprintf("openapirouter: Security(%q): %s", name, err))
}
builder.securityHandlers[name] = append(builder.securityHandlers[name], handler)
return builder
}
func (builder *RouterBuilder) CreateRouter() (*echo.Echo, error) {
e := echo.New()
if err := builder.Mount(e); err != nil {
return nil, err
}
return e, nil
}
func (builder *RouterBuilder) Mount(e *echo.Echo) error {
return builder.mount(e, "")
}
func (builder *RouterBuilder) MountAt(e *echo.Echo, prefix string) error {
return builder.mount(e, prefix)
}
func (builder *RouterBuilder) mount(e *echo.Echo, prefix string) error {
if e == nil {
return errors.New("echo instance cannot be nil")
}
group := e.Group(prefix)
for _, middleware := range builder.rootMiddlewares {
group.Use(middleware)
}
group.Use(builder.validationMiddleware(prefix))
return builder.addRoutes(group)
}
func (builder *RouterBuilder) addRoutes(registrar routeRegistrar) error {
for _, route := range builder.orderedRoutes {
echoRoute, err := builder.echoRoute(route)
if err != nil {
return err
}
if _, err := registrar.AddRoute(echoRoute); err != nil {
return err
}
}
return nil
}
func (builder *RouterBuilder) echoRoute(route *OpenAPIRoute) (echo.Route, error) {
middlewares := []echo.MiddlewareFunc{failureMiddleware(route.failureHandlers), metadataMiddleware(route.operation)}
securityMiddleware, err := builder.securityMiddleware(route.operation)
if err != nil {
return echo.Route{}, err
}
if securityMiddleware != nil {
middlewares = append(middlewares, securityMiddleware)
}
middlewares = append(middlewares, route.middlewares...)
handler := notImplementedHandler
if len(route.handlers) > 0 {
handler = routeHandler(route.handlers)
}
return echo.Route{
Method: route.method,
Path: ToEchoPath(route.path),
Name: route.operation.OperationID,
Handler: handler,
Middlewares: middlewares,
}, nil
}
func (builder *RouterBuilder) route(operationID string, method string) *OpenAPIRoute {
if builder == nil {
panic(fmt.Sprintf("openapirouter: %s called on nil RouterBuilder", method))
}
if route := builder.routes[operationID]; route != nil {
return route
}
panic(fmt.Sprintf(
"openapirouter: %s(%q): operationId not found in OpenAPI spec; available operationIds: %s",
method,
operationID,
builder.availableOperationIDs(),
))
}
func (builder *RouterBuilder) availableOperationIDs() string {
operationIDs := make([]string, 0, len(builder.orderedRoutes))
for _, route := range builder.orderedRoutes {
if route == nil || route.operation == nil {
continue
}
operationIDs = append(operationIDs, route.operation.OperationID)
}
if len(operationIDs) == 0 {
return "(none)"
}
return strings.Join(operationIDs, ", ")
}
func ToEchoPath(openAPIPath string) string {
return pathParamRE.ReplaceAllString(openAPIPath, ":$1")
}
func notImplementedHandler(c *echo.Context) error {
return c.NoContent(http.StatusNotImplemented)
}
func (builder *RouterBuilder) collectRoutes() error {
for _, path := range builder.spec.Paths.InMatchingOrder() {
pathItem := builder.spec.Paths.Value(path)
if pathItem == nil {
continue
}
for _, method := range supportedMethods {
operation := pathItem.GetOperation(method)
if operation == nil {
continue
}
if operation.OperationID == "" {
return fmt.Errorf("%s %s has empty operationId", method, path)
}
if _, exists := builder.routes[operation.OperationID]; exists {
return fmt.Errorf("duplicate operationId %q", operation.OperationID)
}
route := newOpenAPIRoute(method, path, operation)
builder.routes[operation.OperationID] = route
builder.orderedRoutes = append(builder.orderedRoutes, route)
}
}
return nil
}
func (builder *RouterBuilder) validationMiddleware(prefix string) echo.MiddlewareFunc {
options := builder.validationOptions
if prefix != "" {
options.Prefix = prefix
}
if options.Options.AuthenticationFunc == nil {
options.Options.AuthenticationFunc = openapi3filter.NoopAuthenticationFunc
}
return validator.OapiRequestValidatorWithOptions(builder.spec, &options)
}
func metadataMiddleware(operation *openapi3.Operation) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
c.Set(KeyOperation, operation)
return next(c)
}
}
}
func routeHandler(handlers []echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
for _, handler := range handlers {
if err := handler(c); err != nil {
return err
}
if responseCommitted(c) {
return nil
}
}
return nil
}
}
var supportedMethods = []string{
http.MethodConnect,
http.MethodDelete,
http.MethodGet,
http.MethodHead,
http.MethodOptions,
http.MethodPatch,
http.MethodPost,
http.MethodPut,
http.MethodTrace,
}