-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
openapi.go
427 lines (366 loc) · 12.3 KB
/
openapi.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
package fuego
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"github.com/getkin/kin-openapi/openapi3"
)
func NewOpenApiSpec() openapi3.T {
info := &openapi3.Info{
Title: "OpenAPI",
Description: openapiDescription,
Version: "0.0.1",
}
spec := openapi3.T{
OpenAPI: "3.1.0",
Info: info,
Paths: &openapi3.Paths{},
Servers: []*openapi3.Server{},
Security: openapi3.SecurityRequirements{},
Components: &openapi3.Components{
Schemas: make(map[string]*openapi3.SchemaRef),
RequestBodies: make(map[string]*openapi3.RequestBodyRef),
Responses: make(map[string]*openapi3.ResponseRef),
},
}
return spec
}
// Hide prevents the routes in this server or group from being included in the OpenAPI spec.
func (s *Server) Hide() *Server {
s.DisableOpenapi = true
return s
}
// Show allows displaying the routes. Activated by default so useless in most cases,
// but this can be useful if you deactivated the parent group.
func (s *Server) Show() *Server {
s.DisableOpenapi = false
return s
}
// OutputOpenAPISpec takes the OpenAPI spec and outputs it to a JSON file and/or serves it on a URL.
// Also serves a Swagger UI.
// To modify its behavior, use the [WithOpenAPIConfig] option.
func (s *Server) OutputOpenAPISpec() openapi3.T {
// Validate
err := s.OpenApiSpec.Validate(context.Background())
if err != nil {
slog.Error("Error validating spec", "error", err)
}
// Marshal spec to JSON
jsonSpec, err := s.marshalSpec()
if err != nil {
slog.Error("Error marshaling spec to JSON", "error", err)
}
if !s.OpenAPIConfig.DisableSwagger {
s.registerOpenAPIRoutes(jsonSpec)
}
if !s.OpenAPIConfig.DisableLocalSave {
err := s.saveOpenAPIToFile(s.OpenAPIConfig.JsonFilePath, jsonSpec)
if err != nil {
slog.Error("Error saving spec to local path", "error", err, "path", s.OpenAPIConfig.JsonFilePath)
}
}
return s.OpenApiSpec
}
func (s *Server) marshalSpec() ([]byte, error) {
if s.OpenAPIConfig.PrettyFormatJson {
return json.MarshalIndent(s.OpenApiSpec, "", " ")
}
return json.Marshal(s.OpenApiSpec)
}
func (s *Server) saveOpenAPIToFile(jsonSpecLocalPath string, jsonSpec []byte) error {
jsonFolder := filepath.Dir(jsonSpecLocalPath)
err := os.MkdirAll(jsonFolder, 0o750)
if err != nil {
return errors.New("error creating docs directory")
}
f, err := os.Create(jsonSpecLocalPath) // #nosec G304 (file path provided by developer, not by user)
if err != nil {
return errors.New("error creating file")
}
defer f.Close()
_, err = f.Write(jsonSpec)
if err != nil {
return errors.New("error writing file ")
}
s.printOpenAPIMessage("JSON file: " + jsonSpecLocalPath)
return nil
}
// Registers the routes to serve the OpenAPI spec and Swagger UI.
func (s *Server) registerOpenAPIRoutes(jsonSpec []byte) {
GetStd(s, s.OpenAPIConfig.JsonUrl, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(jsonSpec)
})
s.printOpenAPIMessage(fmt.Sprintf("JSON spec: %s://%s%s", s.proto(), s.Server.Addr, s.OpenAPIConfig.JsonUrl))
if !s.OpenAPIConfig.DisableSwaggerUI {
Register(s, Route[any, any]{
BaseRoute: BaseRoute{
Method: http.MethodGet,
Path: s.OpenAPIConfig.SwaggerUrl + "/",
},
}, s.OpenAPIConfig.UIHandler(s.OpenAPIConfig.JsonUrl))
s.printOpenAPIMessage(fmt.Sprintf("OpenAPI UI: %s://%s%s/index.html", s.proto(), s.Server.Addr, s.OpenAPIConfig.SwaggerUrl))
}
}
func (s *Server) printOpenAPIMessage(msg string) {
if !s.disableStartupMessages {
slog.Info(msg)
}
}
func validateJsonSpecUrl(jsonSpecUrl string) bool {
jsonSpecUrlRegexp := regexp.MustCompile(`^\/[\/a-zA-Z0-9\-\_]+(.json)$`)
return jsonSpecUrlRegexp.MatchString(jsonSpecUrl)
}
func validateSwaggerUrl(swaggerUrl string) bool {
swaggerUrlRegexp := regexp.MustCompile(`^\/[\/a-zA-Z0-9\-\_]+[a-zA-Z0-9\-\_]$`)
return swaggerUrlRegexp.MatchString(swaggerUrl)
}
// RegisterOpenAPIOperation registers an OpenAPI operation.
func RegisterOpenAPIOperation[T, B any](s *Server, route Route[T, B]) (*openapi3.Operation, error) {
if route.Operation == nil {
route.Operation = openapi3.NewOperation()
}
if s.tags != nil {
route.Operation.Tags = append(route.Operation.Tags, s.tags...)
}
// Tags
if !s.disableAutoGroupTags && s.groupTag != "" {
route.Operation.Tags = append(route.Operation.Tags, s.groupTag)
}
for _, param := range s.params {
route.Param(param.Type, param.Name, param.Description, param.OpenAPIParamOption)
}
// Request Body
if route.Operation.RequestBody == nil {
bodyTag := SchemaTagFromType(s, *new(B))
if bodyTag.Name != "unknown-interface" {
requestBody := newRequestBody[B](bodyTag, route.AcceptedContentTypes)
// add request body to operation
route.Operation.RequestBody = &openapi3.RequestBodyRef{
Value: requestBody,
}
}
}
// Response - globals
for _, openAPIGlobalResponse := range s.globalOpenAPIResponses {
addResponse(s, route.Operation, openAPIGlobalResponse.Code, openAPIGlobalResponse.Description, openAPIGlobalResponse.ErrorType)
}
// Response - 200
responseSchema := SchemaTagFromType(s, *new(T))
content := openapi3.NewContentWithSchemaRef(&responseSchema.SchemaRef, []string{"application/json", "application/xml"})
response := openapi3.NewResponse().WithDescription("OK").WithContent(content)
route.Operation.AddResponse(200, response)
// Path parameters
for _, pathParam := range parsePathParams(route.Path) {
parameter := openapi3.NewPathParameter(pathParam)
parameter.Schema = openapi3.NewStringSchema().NewRef()
if strings.HasSuffix(pathParam, "...") {
parameter.Description += " (might contain slashes)"
}
route.Operation.AddParameter(parameter)
}
s.OpenApiSpec.AddOperation(route.Path, route.Method, route.Operation)
return route.Operation, nil
}
func newRequestBody[RequestBody any](tag SchemaTag, consumes []string) *openapi3.RequestBody {
content := openapi3.NewContentWithSchemaRef(&tag.SchemaRef, consumes)
return openapi3.NewRequestBody().
WithRequired(true).
WithDescription("Request body for " + reflect.TypeOf(*new(RequestBody)).String()).
WithContent(content)
}
// SchemaTag is a struct that holds the name of the struct and the associated openapi3.SchemaRef
type SchemaTag struct {
openapi3.SchemaRef
Name string
}
func SchemaTagFromType(s *Server, v any) SchemaTag {
if v == nil {
// ensure we add unknown-interface to our schemas
schema := s.getOrCreateSchema("unknown-interface", struct{}{})
return SchemaTag{
Name: "unknown-interface",
SchemaRef: openapi3.SchemaRef{
Ref: "#/components/schemas/unknown-interface",
Value: schema,
},
}
}
return dive(s, reflect.TypeOf(v), SchemaTag{}, 5)
}
// dive returns a schemaTag which includes the generated openapi3.SchemaRef and
// the name of the struct being passed in.
// If the type is a pointer, map, channel, function, or unsafe pointer,
// it will dive into the type and return the name of the type it points to.
// If the type is a slice or array type it will dive into the type as well as
// build and openapi3.Schema where Type is array and Ref is set to the proper
// components Schema
func dive(s *Server, t reflect.Type, tag SchemaTag, maxDepth int) SchemaTag {
if maxDepth == 0 {
return SchemaTag{
Name: "default",
SchemaRef: openapi3.SchemaRef{
Ref: "#/components/schemas/default",
},
}
}
switch t.Kind() {
case reflect.Ptr, reflect.Map, reflect.Chan, reflect.Func, reflect.UnsafePointer:
return dive(s, t.Elem(), tag, maxDepth-1)
case reflect.Slice, reflect.Array:
item := dive(s, t.Elem(), tag, maxDepth-1)
tag.Name = item.Name
tag.Value = openapi3.NewArraySchema()
tag.Value.Items = &item.SchemaRef
return tag
default:
tag.Name = t.Name()
if t.Kind() == reflect.Struct && strings.HasPrefix(tag.Name, "DataOrTemplate") {
return dive(s, t.Field(0).Type, tag, maxDepth-1)
}
tag.Ref = "#/components/schemas/" + tag.Name
tag.Value = s.getOrCreateSchema(tag.Name, reflect.New(t).Interface())
return tag
}
}
// getOrCreateSchema is used to get a schema from the OpenAPI spec.
// If the schema does not exist, it will create a new schema and add it to the OpenAPI spec.
func (s *Server) getOrCreateSchema(key string, v any) *openapi3.Schema {
schemaRef, ok := s.OpenApiSpec.Components.Schemas[key]
if !ok {
schemaRef = s.createSchema(key, v)
}
return schemaRef.Value
}
// createSchema is used to create a new schema and add it to the OpenAPI spec.
// Relies on the openapi3gen package to generate the schema, and adds custom struct tags.
func (s *Server) createSchema(key string, v any) *openapi3.SchemaRef {
schemaRef, err := s.openAPIGenerator.NewSchemaRefForValue(v, s.OpenApiSpec.Components.Schemas)
if err != nil {
slog.Error("Error generating schema", "key", key, "error", err)
}
schemaRef.Value.Description = key + " schema"
descriptionable, ok := v.(OpenAPIDescriptioner)
if ok {
schemaRef.Value.Description = descriptionable.Description()
}
s.parseStructTags(reflect.TypeOf(v), schemaRef)
s.OpenApiSpec.Components.Schemas[key] = schemaRef
return schemaRef
}
// parseStructTags parses struct tags and modifies the schema accordingly.
// t must be a struct type.
// It adds the following struct tags (tag => OpenAPI schema field):
// - description => description
// - example => example
// - json => nullable (if contains omitempty)
// - validate:
// - required => required
// - min=1 => min=1 (for integers)
// - min=1 => minLength=1 (for strings)
// - max=100 => max=100 (for integers)
// - max=100 => maxLength=100 (for strings)
func (s *Server) parseStructTags(t reflect.Type, schemaRef *openapi3.SchemaRef) {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return
}
for i := range t.NumField() {
field := t.Field(i)
if field.Anonymous {
fieldType := field.Type
s.parseStructTags(fieldType, schemaRef)
continue
}
jsonFieldName := field.Tag.Get("json")
jsonFieldName = strings.Split(jsonFieldName, ",")[0] // remove omitempty, etc
if jsonFieldName == "-" {
continue
}
if jsonFieldName == "" {
jsonFieldName = field.Name
}
property := schemaRef.Value.Properties[jsonFieldName]
if property == nil {
slog.Warn("Property not found in schema", "property", jsonFieldName)
continue
}
propertyCopy := *property
propertyValue := *propertyCopy.Value
// Example
example, ok := field.Tag.Lookup("example")
if ok {
propertyValue.Example = example
if propertyValue.Type.Is(openapi3.TypeInteger) {
exNum, err := strconv.Atoi(example)
if err != nil {
slog.Warn("Example might be incorrect (should be integer)", "error", err)
}
propertyValue.Example = exNum
}
}
// Validation
validateTag, ok := field.Tag.Lookup("validate")
validateTags := strings.Split(validateTag, ",")
if ok && slices.Contains(validateTags, "required") {
schemaRef.Value.Required = append(schemaRef.Value.Required, jsonFieldName)
}
for _, validateTag := range validateTags {
if strings.HasPrefix(validateTag, "min=") {
min, err := strconv.Atoi(strings.Split(validateTag, "=")[1])
if err != nil {
slog.Warn("Min might be incorrect (should be integer)", "error", err)
}
if propertyValue.Type.Is(openapi3.TypeInteger) {
minPtr := float64(min)
propertyValue.Min = &minPtr
} else if propertyValue.Type.Is(openapi3.TypeString) {
//nolint:gosec // disable G115
propertyValue.MinLength = uint64(min)
}
}
if strings.HasPrefix(validateTag, "max=") {
max, err := strconv.Atoi(strings.Split(validateTag, "=")[1])
if err != nil {
slog.Warn("Max might be incorrect (should be integer)", "error", err)
}
if propertyValue.Type.Is(openapi3.TypeInteger) {
maxPtr := float64(max)
propertyValue.Max = &maxPtr
} else if propertyValue.Type.Is(openapi3.TypeString) {
//nolint:gosec // disable G115
maxPtr := uint64(max)
propertyValue.MaxLength = &maxPtr
}
}
}
// Description
description, ok := field.Tag.Lookup("description")
if ok {
propertyValue.Description = description
}
jsonTag, ok := field.Tag.Lookup("json")
if ok {
if strings.Contains(jsonTag, ",omitempty") {
propertyValue.Nullable = true
}
}
propertyCopy.Value = &propertyValue
schemaRef.Value.Properties[jsonFieldName] = &propertyCopy
}
}
type OpenAPIDescriptioner interface {
Description() string
}