-
Notifications
You must be signed in to change notification settings - Fork 0
/
fizz.go
463 lines (407 loc) · 13.1 KB
/
fizz.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package fizz
import (
"context"
"errors"
"fmt"
"net/http"
"path"
"reflect"
"runtime"
"strings"
"time"
"github.com/ccfish86/fizz/v2/openapi"
"github.com/ccfish86/gadgeto/tonic"
"github.com/gin-gonic/gin"
)
const ctxOpenAPIOperation = "_ctx_openapi_operation"
// Primitive type helpers.
var (
Integer int32
Long int64
Float float32
Double float64
String string
Byte []byte
Binary []byte
Boolean bool
DateTime time.Time
)
// Fizz is an abstraction of a Gin engine that wraps the
// routes handlers with Tonic and generates an OpenAPI
// 3.0 specification from it.
type Fizz struct {
gen *openapi.Generator
engine *gin.Engine
*RouterGroup
}
// RouterGroup is an abstraction of a Gin router group.
type RouterGroup struct {
group *gin.RouterGroup
gen *openapi.Generator
Name string
Description string
postHandler PostHandlerFunc
}
// PostHandlerFunc is a function that is called after a handler is registered.
type PostHandlerFunc func(method, path, summary, basePath, groupName, groupDescription string)
// New creates a new Fizz wrapper for
// a default Gin engine.
func New() *Fizz {
return NewFromEngine(gin.New())
}
// NewFromEngine creates a new Fizz wrapper
// from an existing Gin engine.
func NewFromEngine(e *gin.Engine) *Fizz {
// Create a new spec with the config
// based on tonic internals.
gen, _ := openapi.NewGenerator(
&openapi.SpecGenConfig{
ValidatorTag: tonic.ValidationTag,
PathLocationTag: tonic.PathTag,
QueryLocationTag: tonic.QueryTag,
FormLocationTag: "form",
HeaderLocationTag: tonic.HeaderTag,
EnumTag: tonic.EnumTag,
DefaultTag: tonic.DefaultTag,
},
)
return &Fizz{
engine: e,
gen: gen,
RouterGroup: &RouterGroup{
group: &e.RouterGroup,
gen: gen,
},
}
}
// ServeHTTP implements http.HandlerFunc for Fizz.
func (f *Fizz) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.engine.ServeHTTP(w, r)
}
// Engine returns the underlying Gin engine.
func (f *Fizz) Engine() *gin.Engine {
return f.engine
}
// GinRouterGroup returns the underlying Gin router group.
func (f *Fizz) GinRouterGroup() *gin.RouterGroup {
return f.group
}
// Generator returns the underlying OpenAPI generator.
func (f *Fizz) Generator() *openapi.Generator {
return f.gen
}
// Errors returns the errors that may have occurred
// during the spec generation.
func (f *Fizz) Errors() []error {
return f.gen.Errors()
}
// Group creates a new group of routes.
func (g *RouterGroup) Group(path, name, description string, handlers ...gin.HandlerFunc) *RouterGroup {
// Create the tag in the specification
// for this groups.
g.gen.AddTag(name, description)
return &RouterGroup{
gen: g.gen,
group: g.group.Group(path, handlers...),
postHandler: g.postHandler,
Name: name,
Description: description,
}
}
// Use adds middleware to the group.
func (g *RouterGroup) Use(handlers ...gin.HandlerFunc) {
g.group.Use(handlers...)
}
// GinRouterGroup returns the underlying Gin router group.
func (g *RouterGroup) GinRouterGroup() *gin.RouterGroup {
return g.group
}
// GET is a shortcut to register a new handler with the GET method.
func (g *RouterGroup) GET(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
return g.Handle(path, "GET", infos, handlers...)
}
// POST is a shortcut to register a new handler with the POST method.
func (g *RouterGroup) POST(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
return g.Handle(path, "POST", infos, handlers...)
}
// PUT is a shortcut to register a new handler with the PUT method.
func (g *RouterGroup) PUT(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
return g.Handle(path, "PUT", infos, handlers...)
}
// PATCH is a shortcut to register a new handler with the PATCH method.
func (g *RouterGroup) PATCH(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
return g.Handle(path, "PATCH", infos, handlers...)
}
// DELETE is a shortcut to register a new handler with the DELETE method.
func (g *RouterGroup) DELETE(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
return g.Handle(path, "DELETE", infos, handlers...)
}
// OPTIONS is a shortcut to register a new handler with the OPTIONS method.
func (g *RouterGroup) OPTIONS(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
return g.Handle(path, "OPTIONS", infos, handlers...)
}
// HEAD is a shortcut to register a new handler with the HEAD method.
func (g *RouterGroup) HEAD(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
return g.Handle(path, "HEAD", infos, handlers...)
}
// TRACE is a shortcut to register a new handler with the TRACE method.
func (g *RouterGroup) TRACE(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
return g.Handle(path, "TRACE", infos, handlers...)
}
// Handle registers a new request handler that is wrapped
// with Tonic and documented in the OpenAPI specification.
func (g *RouterGroup) Handle(path, method string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup {
oi := &openapi.OperationInfo{}
for _, info := range infos {
info(oi)
}
type wrap struct {
h gin.HandlerFunc
r *tonic.Route
}
var wrapped []wrap
// Find the handlers wrapped with Tonic.
for _, h := range handlers {
r, err := tonic.GetRouteByHandler(h)
if err == nil {
wrapped = append(wrapped, wrap{h: h, r: r})
}
}
// Check that no more that one tonic-wrapped handler
// is registered for this operation.
if len(wrapped) > 1 {
panic(fmt.Sprintf("multiple tonic-wrapped handler used for operation %s %s", method, path))
}
// If we have a tonic-wrapped handler, generate the
// specification of this operation.
if len(wrapped) == 1 {
hfunc := wrapped[0].r
// Set an operation ID if none is provided.
if oi.ID == "" {
oi.ID = hfunc.HandlerName()
}
oi.StatusCode = hfunc.GetDefaultStatusCode()
requestMediaType := hfunc.GetRequestMediaType()
if requestMediaType == "" {
requestMediaType = tonic.MediaType()
}
responseMediaType := hfunc.GetResponseMediaType()
if responseMediaType == "" {
responseMediaType = tonic.MediaType()
}
// Set an input type if provided.
it := hfunc.InputType()
if oi.InputModel != nil {
it = reflect.TypeOf(oi.InputModel)
}
// Consolidate path for OpenAPI spec.
operationPath := joinPaths(g.group.BasePath(), path)
// Add operation to the OpenAPI spec.
operation, err := g.gen.AddOperation(operationPath, method, g.Name, requestMediaType, responseMediaType, it, hfunc.OutputType(), oi)
if err != nil {
panic(fmt.Sprintf(
"error while generating OpenAPI spec on operation %s %s: %s",
method, path, err,
))
}
// If an operation was generated for the handler,
// wrap the Tonic-wrapped handled with a closure
// to inject it into the Gin context.
if operation != nil {
for i, h := range handlers {
if funcEqual(h, wrapped[0].h) {
orig := h // copy the original func
handlers[i] = func(c *gin.Context) {
c.Set(ctxOpenAPIOperation, operation)
orig(c)
}
}
}
}
}
// Register the handlers with Gin underlying group.
g.group.Handle(method, path, handlers...)
if g.postHandler != nil {
g.postHandler(method, path, oi.Summary, g.group.BasePath(), g.Name, g.Description)
}
return g
}
// PostHandler sets a function that is called after a handler is registered.
func (g *RouterGroup) PostHandler(f PostHandlerFunc) {
g.postHandler = f
}
// OpenAPI returns a Gin HandlerFunc that serves
// the marshalled OpenAPI specification of the API.
func (f *Fizz) OpenAPI(info *openapi.Info, ct string) gin.HandlerFunc {
f.gen.SetInfo(info)
ct = strings.ToLower(ct)
if ct == "" {
ct = "json"
}
switch ct {
case "json":
return func(c *gin.Context) {
c.JSON(200, f.gen.API())
}
case "yaml":
return func(c *gin.Context) {
c.YAML(200, f.gen.API())
}
}
panic("invalid content type, use JSON or YAML")
}
// OperationOption represents an option-pattern function
// used to add informations to an operation.
type OperationOption func(*openapi.OperationInfo)
// StatusDescription sets the default status description of the operation.
func StatusDescription(desc string) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.StatusDescription = desc
}
}
// Summary adds a summary to an operation.
func Summary(summary string) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Summary = summary
}
}
// Summaryf adds a summary to an operation according
// to a format specifier.
func Summaryf(format string, a ...interface{}) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Summary = fmt.Sprintf(format, a...)
}
}
// Description adds a description to an operation.
func Description(desc string) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Description = desc
}
}
// Descriptionf adds a description to an operation
// according to a format specifier.
func Descriptionf(format string, a ...interface{}) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Description = fmt.Sprintf(format, a...)
}
}
// ID overrides the operation ID.
func ID(id string) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.ID = id
}
}
// Deprecated marks the operation as deprecated.
func Deprecated(deprecated bool) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Deprecated = deprecated
}
}
// Response adds an additional response to the operation.
func Response(statusCode, desc string, model interface{}, headers []*openapi.ResponseHeader, example interface{}) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Responses = append(o.Responses, &openapi.OperationResponse{
Code: statusCode,
Description: desc,
Model: model,
Headers: headers,
Example: example,
})
}
}
// ResponseWithExamples is a variant of Response that accept many examples.
func ResponseWithExamples(statusCode, desc string, model interface{}, headers []*openapi.ResponseHeader, examples map[string]interface{}) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Responses = append(o.Responses, &openapi.OperationResponse{
Code: statusCode,
Description: desc,
Model: model,
Headers: headers,
Examples: examples,
})
}
}
// Header adds a header to the operation.
func Header(name, desc string, model interface{}) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Headers = append(o.Headers, &openapi.ResponseHeader{
Name: name,
Description: desc,
Model: model,
})
}
}
// InputModel overrides the binding model of the operation.
func InputModel(model interface{}) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.InputModel = model
}
}
// XCodeSample adds a code sample to the operation.
func XCodeSample(cs *openapi.XCodeSample) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.XCodeSamples = append(o.XCodeSamples, cs)
}
}
// Overrides top-level security requirement for this operation.
// Note that this function can be used more than once to add several requirements.
func Security(security *openapi.SecurityRequirement) func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Security = append(o.Security, security)
}
}
// Add an empty security requirement to this operation to make other security requirements optional.
func WithOptionalSecurity() func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
var emptyRequirement openapi.SecurityRequirement = make(openapi.SecurityRequirement)
o.Security = append(o.Security, &emptyRequirement)
}
}
// Remove any top-level security requirements for this operation.
func WithoutSecurity() func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.Security = []*openapi.SecurityRequirement{}
}
}
// XInternal marks the operation as internal.
func XInternal() func(*openapi.OperationInfo) {
return func(o *openapi.OperationInfo) {
o.XInternal = true
}
}
// OperationFromContext returns the OpenAPI operation from
// the given Gin context or an error if none is found.
func OperationFromContext(ctx context.Context) (*openapi.Operation, error) {
if v := ctx.Value(ctxOpenAPIOperation); v != nil {
if op, ok := v.(*openapi.Operation); ok {
return op, nil
}
return nil, errors.New("invalid type: not an operation")
}
return nil, errors.New("operation not found")
}
func joinPaths(abs, rel string) string {
if rel == "" {
return abs
}
final := path.Join(abs, rel)
as := lastChar(rel) == '/' && lastChar(final) != '/'
if as {
return final + "/"
}
return final
}
func lastChar(str string) uint8 {
if str == "" {
panic("empty string")
}
return str[len(str)-1]
}
func funcEqual(f1, f2 interface{}) bool {
v1 := reflect.ValueOf(f1)
v2 := reflect.ValueOf(f2)
if v1.Kind() == reflect.Func && v2.Kind() == reflect.Func { // prevent panic on call to Pointer()
return runtime.FuncForPC(v1.Pointer()).Entry() == runtime.FuncForPC(v2.Pointer()).Entry()
}
return false
}