-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
route.go
82 lines (64 loc) · 2.23 KB
/
route.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package fuego
import (
"net/http"
"strings"
"github.com/getkin/kin-openapi/openapi3"
)
func NewRoute[T, B any](method, path string, handler any, openapi *OpenAPI, options ...func(*BaseRoute)) Route[T, B] {
return Route[T, B]{
BaseRoute: NewBaseRoute(method, path, handler, openapi, options...),
}
}
// Route is the main struct for a route in Fuego.
// It contains the OpenAPI operation and other metadata.
// It is a wrapper around BaseRoute, with the addition of the response and request body types.
type Route[ResponseBody any, RequestBody any] struct {
BaseRoute
}
func NewBaseRoute(method, path string, handler any, openapi *OpenAPI, options ...func(*BaseRoute)) BaseRoute {
baseRoute := BaseRoute{
Method: method,
Path: path,
Params: make(map[string]OpenAPIParam),
FullName: FuncName(handler),
Operation: openapi3.NewOperation(),
OpenAPI: openapi,
}
for _, o := range options {
o(&baseRoute)
}
return baseRoute
}
// BaseRoute is the base struct for all routes in Fuego.
// It contains the OpenAPI operation and other metadata.
type BaseRoute struct {
// OpenAPI operation
Operation *openapi3.Operation
// HTTP method (GET, POST, PUT, PATCH, DELETE)
Method string
// URL path. Will be prefixed by the base path of the server and the group path if any
Path string
// namespace and name of the function to execute
FullName string
Params map[string]OpenAPIParam
Middlewares []func(http.Handler) http.Handler
// Content types accepted for the request body. If nil, all content types (*/*) are accepted.
AcceptedContentTypes []string
// If true, the route will not be documented in the OpenAPI spec
Hidden bool
// Default status code for the response
DefaultStatusCode int
// Ref to the whole OpenAPI spec. Be careful when changing directly its value directly.
OpenAPI *OpenAPI
// Override the default description
overrideDescription bool
}
func (r *BaseRoute) GenerateDefaultDescription() {
if r.overrideDescription {
return
}
r.Operation.Description = DefaultDescription(r.FullName, r.Middlewares) + r.Operation.Description
}
func (r *BaseRoute) GenerateDefaultOperationID() {
r.Operation.OperationID = r.Method + "_" + strings.ReplaceAll(strings.ReplaceAll(r.Path, "{", ":"), "}", "")
}