-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
option.go
440 lines (395 loc) · 13.9 KB
/
option.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
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package fuego
import (
"fmt"
"net/http"
"strconv"
"github.com/getkin/kin-openapi/openapi3"
)
// Group allows to group routes under a common path.
// Useful to group often used middlewares or options and reuse them.
// Example:
//
// optionsPagination := option.Group(
// option.QueryInt("per_page", "Number of items per page", ParamRequired()),
// option.QueryInt("page", "Page number", ParamDefault(1)),
// )
func GroupOptions(options ...func(*BaseRoute)) func(*BaseRoute) {
return func(r *BaseRoute) {
for _, option := range options {
option(r)
}
}
}
// Middleware adds one or more route-scoped middleware.
func OptionMiddleware(middleware ...func(http.Handler) http.Handler) func(*BaseRoute) {
return func(r *BaseRoute) {
r.Middlewares = append(r.Middlewares, middleware...)
}
}
// Declare a query parameter for the route.
// This will be added to the OpenAPI spec.
// Example:
//
// Query("name", "Filter by name", ParamExample("cat name", "felix"), ParamNullable())
//
// The list of options is in the param package.
func OptionQuery(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute) {
options = append(options, ParamDescription(description), paramType(QueryParamType), ParamString())
return func(r *BaseRoute) {
OptionParam(name, options...)(r)
}
}
// Declare an integer query parameter for the route.
// This will be added to the OpenAPI spec.
// The query parameter is transmitted as a string in the URL, but it is parsed as an integer.
// Example:
//
// QueryInt("age", "Filter by age (in years)", ParamExample("3 years old", 3), ParamNullable())
//
// The list of options is in the param package.
func OptionQueryInt(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute) {
options = append(options, ParamDescription(description), paramType(QueryParamType), ParamInteger())
return func(r *BaseRoute) {
OptionParam(name, options...)(r)
}
}
// Declare a boolean query parameter for the route.
// This will be added to the OpenAPI spec.
// The query parameter is transmitted as a string in the URL, but it is parsed as a boolean.
// Example:
//
// QueryBool("is_active", "Filter by active status", ParamExample("true", true), ParamNullable())
//
// The list of options is in the param package.
func OptionQueryBool(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute) {
options = append(options, ParamDescription(description), paramType(QueryParamType), ParamBool())
return func(r *BaseRoute) {
OptionParam(name, options...)(r)
}
}
// Declare a header parameter for the route.
// This will be added to the OpenAPI spec.
// Example:
//
// Header("Authorization", "Bearer token", ParamRequired())
//
// The list of options is in the param package.
func OptionHeader(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute) {
options = append(options, ParamDescription(description), paramType(HeaderParamType))
return func(r *BaseRoute) {
OptionParam(name, options...)(r)
}
}
// Declare a cookie parameter for the route.
// This will be added to the OpenAPI spec.
// Example:
//
// Cookie("session_id", "Session ID", ParamRequired())
//
// The list of options is in the param package.
func OptionCookie(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute) {
options = append(options, ParamDescription(description), paramType(CookieParamType))
return func(r *BaseRoute) {
OptionParam(name, options...)(r)
}
}
// Declare a path parameter for the route.
// This will be added to the OpenAPI spec.
// It will be marked as required by default by Fuego.
// Example:
//
// Path("id", "ID of the item")
//
// The list of options is in the param package.
func OptionPath(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute) {
options = append(options, ParamDescription(description), paramType(PathParamType), ParamRequired())
return func(r *BaseRoute) {
OptionParam(name, options...)(r)
}
}
func paramType(paramType ParamType) func(*OpenAPIParam) {
return func(param *OpenAPIParam) {
param.Type = paramType
}
}
func panicsIfNotCorrectType(openapiParam *openapi3.Parameter, exampleValue any) any {
if exampleValue == nil {
return nil
}
if openapiParam.Schema.Value.Type.Is("integer") {
_, ok := exampleValue.(int)
if !ok {
panic("example value must be an integer")
}
}
if openapiParam.Schema.Value.Type.Is("boolean") {
_, ok := exampleValue.(bool)
if !ok {
panic("example value must be a boolean")
}
}
if openapiParam.Schema.Value.Type.Is("string") {
_, ok := exampleValue.(string)
if !ok {
panic("example value must be a string")
}
}
return exampleValue
}
// Declare a response header for the route.
// This will be added to the OpenAPI spec, under the given default status code response.
// Example:
//
// ResponseHeader("Content-Range", "Pagination range", ParamExample("42 pets", "unit 0-9/42"), ParamDescription("https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range"))
// ResponseHeader("Set-Cookie", "Session cookie", ParamExample("session abc123", "session=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT"))
//
// The list of options is in the param package.
func OptionResponseHeader(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute) {
apiParam, openapiParam := buildParam(name, options...)
openapiParam.Name = ""
openapiParam.In = ""
if len(apiParam.StatusCodes) == 0 {
apiParam.StatusCodes = []int{200}
}
return func(r *BaseRoute) {
for _, code := range apiParam.StatusCodes {
codeString := strconv.Itoa(code)
responseForCurrentCode := r.Operation.Responses.Value(codeString)
if responseForCurrentCode == nil {
response := openapi3.NewResponse().WithDescription("OK")
r.Operation.AddResponse(code, response)
responseForCurrentCode = r.Operation.Responses.Value(codeString)
}
responseForCurrentCodeHeaders := responseForCurrentCode.Value.Headers
if responseForCurrentCodeHeaders == nil {
responseForCurrentCode.Value.Headers = make(map[string]*openapi3.HeaderRef)
}
responseForCurrentCode.Value.Headers[name] = &openapi3.HeaderRef{
Value: &openapi3.Header{
Parameter: *openapiParam,
},
}
}
}
}
func buildParam(name string, options ...func(*OpenAPIParam)) (OpenAPIParam, *openapi3.Parameter) {
param := OpenAPIParam{
Name: name,
}
// Applies options to OpenAPIParam
for _, option := range options {
option(¶m)
}
// Applies OpenAPIParam to openapi3.Parameter
// Why not use openapi3.NewHeaderParameter(name) directly?
// Because we might change the openapi3 library in the future,
// and we want to keep the flexibility to change the implementation without changing the API.
openapiParam := &openapi3.Parameter{
Name: name,
In: string(param.Type),
Description: param.Description,
Schema: openapi3.NewStringSchema().NewRef(),
}
if param.GoType != "" {
openapiParam.Schema.Value.Type = &openapi3.Types{param.GoType}
}
openapiParam.Schema.Value.Nullable = param.Nullable
openapiParam.Schema.Value.Default = panicsIfNotCorrectType(openapiParam, param.Default)
if param.Required {
openapiParam.Required = param.Required
}
for name, exampleValue := range param.Examples {
if openapiParam.Examples == nil {
openapiParam.Examples = make(openapi3.Examples)
}
exampleOpenAPI := openapi3.NewExample(name)
exampleOpenAPI.Value = panicsIfNotCorrectType(openapiParam, exampleValue)
openapiParam.Examples[name] = &openapi3.ExampleRef{Value: exampleOpenAPI}
}
return param, openapiParam
}
// Registers a parameter for the route. Prefer using the [Query], [QueryInt], [Header], [Cookie] shortcuts.
func OptionParam(name string, options ...func(*OpenAPIParam)) func(*BaseRoute) {
param, openapiParam := buildParam(name, options...)
return func(r *BaseRoute) {
r.Operation.AddParameter(openapiParam)
if r.Params == nil {
r.Params = make(map[string]OpenAPIParam)
}
r.Params[name] = param
}
}
// Tags adds one or more tags to the route.
func OptionTags(tags ...string) func(*BaseRoute) {
return func(r *BaseRoute) {
r.Operation.Tags = append(r.Operation.Tags, tags...)
}
}
// Summary adds a summary to the route.
func OptionSummary(summary string) func(*BaseRoute) {
return func(r *BaseRoute) {
r.Operation.Summary = summary
}
}
// OptionOverrideDescription overrides the default description set by Fuego.
// By default, the description is set by Fuego with some info,
// like the controller function name and the package name.
func OptionDescription(description string) func(*BaseRoute) {
return func(r *BaseRoute) {
r.Operation.Description = description
}
}
// Description appends a description to the route.
// By default, the description is set by Fuego with some info,
// like the controller function name and the package name.
func OptionAddDescription(description string) func(*BaseRoute) {
return func(r *BaseRoute) {
r.Operation.Description += description
}
}
// OptionOverrideDescription overrides the default description set by Fuego.
// By default, the description is set by Fuego with some info,
// like the controller function name and the package name.
func OptionOverrideDescription(description string) func(*BaseRoute) {
return func(r *BaseRoute) {
r.overrideDescription = true
r.Operation.Description = description
}
}
// OperationID adds an operation ID to the route.
func OptionOperationID(operationID string) func(*BaseRoute) {
return func(r *BaseRoute) {
r.Operation.OperationID = operationID
}
}
// OptionDeprecated marks the route as deprecated.
func OptionDeprecated() func(*BaseRoute) {
return func(r *BaseRoute) {
r.Operation.Deprecated = true
}
}
// AddError adds an error to the route.
// It replaces any existing error previously set with the same code.
// Required: should only supply one type to `errorType`
// Deprecated: Use [OptionAddResponse] instead
func OptionAddError(code int, description string, errorType ...any) func(*BaseRoute) {
var responseSchema SchemaTag
return func(r *BaseRoute) {
if len(errorType) > 1 {
panic("errorType should not be more than one")
}
if len(errorType) > 0 {
responseSchema = SchemaTagFromType(r.OpenAPI, errorType[0])
} else {
responseSchema = SchemaTagFromType(r.OpenAPI, HTTPError{})
}
content := openapi3.NewContentWithSchemaRef(&responseSchema.SchemaRef, []string{"application/json"})
response := openapi3.NewResponse().
WithDescription(description).
WithContent(content)
if r.Operation.Responses == nil {
r.Operation.Responses = openapi3.NewResponses()
}
r.Operation.Responses.Set(strconv.Itoa(code), &openapi3.ResponseRef{Value: response})
}
}
// Response represents a fuego.Response that can be used
// when setting custom response types on routes
type Response struct {
// content-type of the response i.e application/json
ContentTypes []string
// user provided type
Type any
}
// AddResponse adds a response to a route by status code
// It replaces any existing response set by any status code, this will override 200.
// Required: Response.Type must be set
// Optional: Response.ContentTypes will default to `application/json` and `application/xml` if not set
func OptionAddResponse(code int, description string, response Response) func(*BaseRoute) {
return func(r *BaseRoute) {
if r.Operation.Responses == nil {
r.Operation.Responses = openapi3.NewResponses()
}
r.Operation.Responses.Set(
strconv.Itoa(code), &openapi3.ResponseRef{
Value: r.OpenAPI.buildOpenapi3Response(description, response),
},
)
}
}
// RequestContentType sets the accepted content types for the route.
// By default, the accepted content types is */*.
// This will override any options set at the server level.
func OptionRequestContentType(consumes ...string) func(*BaseRoute) {
return func(r *BaseRoute) {
r.AcceptedContentTypes = consumes
}
}
// Hide hides the route from the OpenAPI spec.
func OptionHide() func(*BaseRoute) {
return func(r *BaseRoute) {
r.Hidden = true
}
}
// Show shows the route from the OpenAPI spec.
func OptionShow() func(*BaseRoute) {
return func(r *BaseRoute) {
r.Hidden = false
}
}
// OptionDefaultStatusCode sets the default status code for the route.
func OptionDefaultStatusCode(defaultStatusCode int) func(*BaseRoute) {
return func(r *BaseRoute) {
r.DefaultStatusCode = defaultStatusCode
}
}
// OptionSecurity configures security requirements to the route.
//
// Single Scheme (AND Logic):
//
// Add a single security requirement with multiple schemes.
// All schemes must be satisfied:
// OptionSecurity(openapi3.SecurityRequirement{
// "basic": [], // Requires basic auth
// "oauth2": ["read"] // AND requires oauth with read scope
// })
//
// Multiple Schemes (OR Logic):
//
// Add multiple security requirements.
// At least one requirement must be satisfied:
// OptionSecurity(
// openapi3.SecurityRequirement{"basic": []}, // First option
// openapi3.SecurityRequirement{"oauth2": ["read"]} // Alternative option
// })
//
// Mixing Approaches:
//
// Combine AND logic within requirements and OR logic between requirements:
// OptionSecurity(
// openapi3.SecurityRequirement{
// "basic": [], // Requires basic auth
// "oauth2": ["read:user"] // AND oauth with read:user scope
// },
// openapi3.SecurityRequirement{"apiKey": []} // OR alternative with API key
// })
func OptionSecurity(securityRequirements ...openapi3.SecurityRequirement) func(*BaseRoute) {
return func(r *BaseRoute) {
if r.OpenAPI.Description().Components == nil {
panic("zero security schemes have been registered with the server")
}
// Validate the security scheme exists in components
for _, req := range securityRequirements {
for schemeName := range req {
if _, exists := r.OpenAPI.Description().Components.SecuritySchemes[schemeName]; !exists {
panic(fmt.Sprintf("security scheme '%s' not defined in components", schemeName))
}
}
}
if r.Operation.Security == nil {
r.Operation.Security = &openapi3.SecurityRequirements{}
}
// Append all provided security requirements
*r.Operation.Security = append(*r.Operation.Security, securityRequirements...)
}
}