/
open_api.go
503 lines (451 loc) · 14.3 KB
/
open_api.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
package grest
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
// OpenAPI represents the OpenAPI specification structure.
// The full Latest OpenAPI Specification is available on https://spec.openapis.org/oas/latest.html
type OpenAPI struct {
OpenAPI string `json:"openapi,omitempty"`
Info OpenAPIInfo `json:"info,omitempty"`
JsonSchemaDialect string `json:"jsonSchemaDialect,omitempty"`
Servers []map[string]any `json:"servers,omitempty"`
Paths map[string]MapSlice `json:"paths,omitempty"`
Webhooks map[string]any `json:"webhooks,omitempty"`
Components map[string]any `json:"components,omitempty"`
Security []map[string]any `json:"security,omitempty"`
Tags []map[string]any `json:"tags,omitempty"`
ExternalDocs OpenAPIExternalDoc `json:"externalDocs,omitempty"`
}
// SetVersion sets the OpenAPI version to "3.0.3".
func (o *OpenAPI) SetVersion() {
o.OpenAPI = "3.0.3"
}
// Configure is a placeholder method for adding OpenAPI documentation.
func (o *OpenAPI) Configure() {
// add your openapi doc here
}
// AddServer adds a server to the OpenAPI specification.
// The full latest specs is available on https://spec.openapis.org/oas/latest.html#server-object
func (o *OpenAPI) AddServer(server map[string]any) {
o.Servers = append(o.Servers, server)
}
// AddTag adds a tag to the OpenAPI specification.
// The full latest specs is available on https://spec.openapis.org/oas/latest.html#tag-object
func (o *OpenAPI) AddTag(tag map[string]any) {
tagName, ok := tag["name"].(string)
if ok {
isTagNameExists := false
for _, tg := range o.Tags {
existingTagName, _ := tg["name"].(string)
if tagName == existingTagName {
isTagNameExists = true
}
}
if !isTagNameExists {
o.Tags = append(o.Tags, tag)
}
}
}
// AddPath adds a path to the OpenAPI specification.
func (o *OpenAPI) AddPath(key, method string, operationObject any) {
if o.Paths != nil {
path, _ := o.Paths[key]
o.Paths[key] = append(path, map[string]any{"key": method, "value": operationObject})
} else {
o.Paths = map[string]MapSlice{key: {map[string]any{"key": method, "value": operationObject}}}
}
}
// AddWebhook adds a webhook to the OpenAPI specification.
func (o *OpenAPI) AddWebhook(key string, val any) {
if o.Webhooks != nil {
o.Webhooks[key] = val
} else {
o.Webhooks = map[string]any{key: val}
}
}
// AddComponent adds a component to the OpenAPI specification.
// The full latest specs is available on https://spec.openapis.org/oas/latest.html#components-object
func (o *OpenAPI) AddComponent(key string, val any) {
if o.Components != nil {
component, isComponentExists := o.Components[key]
c, cOk := component.(map[string]any)
v, vOk := val.(map[string]any)
if isComponentExists && cOk && vOk {
for name, value := range v {
_, isNameExists := c[name]
if !isNameExists {
c[name] = value
}
}
o.Components[key] = c
} else {
o.Components[key] = val
}
} else {
o.Components = map[string]any{key: val}
}
}
// AddRoute generates and adds an OpenAPI operation for a route.
func (o *OpenAPI) AddRoute(path, method string, op OpenAPIOperationInterface) {
fmt.Println("OpenAPI : add paths", path, method)
operationObject := map[string]any{}
if len(op.OpenAPITags()) > 0 {
tags := op.OpenAPITags()
for _, tagName := range tags {
o.AddTag(map[string]any{"name": tagName})
}
operationObject["tags"] = tags
}
if op.OpenAPISummary() != "" {
operationObject["summary"] = op.OpenAPISummary()
}
if op.OpenAPIDescription() != "" {
operationObject["description"] = op.OpenAPIDescription()
}
externalDocUrl, externalDocDesc := op.OpenAPIExternalDoc()
if externalDocUrl != "" || externalDocDesc != "" {
operationObject["externalDocs"] = map[string]any{
"url": externalDocUrl,
"description": externalDocDesc,
}
}
if op.OpenAPIOperationID() != "" {
operationObject["operationId"] = op.OpenAPIOperationID()
}
params := []map[string]any{}
params = append(params, op.OpenAPIPathParam()...)
params = append(params, op.OpenAPIHeaderParam()...)
params = append(params, op.OpenAPICookieParam()...)
params = append(params, op.OpenAPIQueryParam()...)
if len(params) > 0 {
operationObject["parameters"] = params
}
requestBody := op.OpenAPIBody()
if requestBody != nil {
for k, m := range requestBody {
model, ok := m.(OpenAPISchemaComponent)
if ok {
requestBody[k] = map[string]map[string]any{
"schema": {
"$ref": "#/components/schemas/" + model.OpenAPISchemaName(),
},
}
o.AddComponent("schemas", map[string]any{
model.OpenAPISchemaName(): model.GetOpenAPISchema(),
})
} else {
delete(requestBody, k)
}
}
operationObject["requestBody"] = map[string]any{"content": requestBody}
}
responses := op.OpenAPIResponses()
if responses != nil {
for code, res := range responses {
for key, val := range res {
if key == "content" {
v, ok := val.(map[string]any)
if ok {
for tp, m := range v {
model, mOK := m.(OpenAPISchemaComponent)
if mOK {
responses[code][key] = map[string]map[string]map[string]any{
tp: {
"schema": {
"$ref": "#/components/schemas/" + model.OpenAPISchemaName(),
},
},
}
o.AddComponent("schemas", map[string]any{
model.OpenAPISchemaName(): model.GetOpenAPISchema(),
})
} else {
delete(responses[code], key)
}
}
}
}
}
}
operationObject["responses"] = responses
}
if op.OpenAPICallbacks() != nil {
operationObject["callbacks"] = op.OpenAPICallbacks()
}
if op.OpenAPIDeprecated() {
operationObject["deprecated"] = op.OpenAPIDeprecated()
}
if len(op.OpenAPISecurity()) > 0 {
operationObject["security"] = op.OpenAPISecurity()
}
if len(op.OpenAPIServer()) > 0 {
operationObject["servers"] = op.OpenAPIServer()
}
o.AddPath(path, strings.ToLower(method), operationObject)
}
// Generate generates the OpenAPI specification and writes it to a file.
func (o *OpenAPI) Generate(p ...string) error {
b, err := json.MarshalIndent(o, "", " ")
if err != nil {
return NewError(http.StatusInternalServerError, err.Error())
}
path := "docs/openapi.json"
if len(p) > 0 {
path = p[0]
}
err = os.WriteFile(path, b, 0666)
if err != nil {
return NewError(http.StatusInternalServerError, err.Error())
}
return nil
}
// OpenAPIInfo represents the information section of the OpenAPI specification.
type OpenAPIInfo struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
TermsOfService string `json:"termsOfService,omitempty"`
Contact OpenAPIContact `json:"contact"`
License OpenAPILicense `json:"license"`
Version string `json:"version"`
}
// OpenAPIContact represents the contact information in the OpenAPI info section.
type OpenAPIContact struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Url string `json:"url,omitempty"`
}
// OpenAPILicense represents the license information in the OpenAPI info section.
type OpenAPILicense struct {
Name string `json:"name"`
Url string `json:"url,omitempty"`
}
// OpenAPIExternalDoc represents an external documentation link in the OpenAPI specification.
type OpenAPIExternalDoc struct {
Description string `json:"description,omitempty"`
Url string `json:"url"`
}
// OpenAPIOperationInterface defines the interface for completing the operation object of an endpoint in the OpenAPI document.
// Full specifications are available at: https://spec.openapis.org/oas/latest.html#operation-object
type OpenAPIOperationInterface interface {
// The tags of specific endpoint.
// for example :
// func (Doc) OpenAPITags() []string {
// return []string{"Data Store - Product"}
// }
OpenAPITags() []string
// The summary of specific endpoint.
// for example :
// func (Doc) OpenAPISummary() string {
// return "Create Product"
// }
OpenAPISummary() string
// The description of specific endpoint.
// for example :
// func (Doc) OpenAPISummary() string {
// return "Use this method to create contact"
// }
OpenAPIDescription() string
// The path param of specific endpoint.
// for example, for endpoint PUT /api/products/{ProductID} you can add the path param like this :
// func (Doc) OpenAPIPathParam() []map[string]any {
// return []map[string]any{
// {
// "in": "path",
// "name": "contactID",
// "schema": map[string]any{
// "type": "string",
// },
// },
// }
// }
// Full specs is available on https://spec.openapis.org/oas/latest.html#parameter-object
OpenAPIPathParam() []map[string]any
// The header param of specific endpoint.
// for example :
// func (Doc) OpenAPIHeaderParam() []map[string]any {
// return []map[string]any{
// {
// "in": "header",
// "name": "Content-Language",
// "schema": map[string]any{
// "type": "string",
// },
// "examples": map[string]any{
// "English (US)": map[string]any{
// "value": "en-US",
// },
// "Bahasa Indonesia": map[string]any{
// "value": "id-ID",
// },
// },
// },
// }
// }
// Full specs is available on https://spec.openapis.org/oas/latest.html#parameter-object
OpenAPIHeaderParam() []map[string]any
// The cookie param of specific endpoint.
// for example :
// func (Doc) OpenAPICookieParam() []map[string]any {
// return []map[string]any{
// {
// "in": "header",
// "name": "token",
// "schema": map[string]any{
// "type": "string",
// },
// },
// }
// }
// Full specs is available on https://spec.openapis.org/oas/latest.html#parameter-object
OpenAPICookieParam() []map[string]any
// The query param of specific endpoint.
// for example :
// func (Doc) OpenAPIQueryParam() []map[string]any {
// return []map[string]any{
// {
// "in": "query",
// "name": "params",
// "schema": map[string]any{
// "type": "object",
// "additionalProperties": map[string]any{
// "type": "string",
// },
// },
// "style": "form",
// "explode": true,
// },
// }
// }
// Full specs is available on https://spec.openapis.org/oas/latest.html#parameter-object
OpenAPIQueryParam() []map[string]any
// Body request of specific endpoint.
// example :
// func (Doc) OpenAPIBody() map[string]any {
// return map[string]any{
// "application/json": &Model{}, // will auto create schema $ref: '#/components/schemas/Model' if not exists
// "application/xml": &Model{},
// "application/x-www-form-urlencoded": &Model{},
// }
// }
OpenAPIBody() map[string]any
// Response of specific endpoint.
// example :
// func (Doc) OpenAPIResponses() map[string]map[string]any {
// return map[string]map[string]any{
// "200": {
// "description": "Success",
// "content": map[string]any{
// "application/json": &Model{}, // will auto create schema $ref: '#/components/schemas/Model' if not exists
// "application/xml": &Model{},
// },
// },
// "401": {
// "description": "Unauthorized",
// "content": map[string]any{
// "application/json": &app.UnauthorizedModel, // will auto create schema $ref: '#/components/schemas/app.UnauthorizedModel' if not exists
// "application/xml": &app.UnauthorizedModel,
// },
// },
// }
// }
// Full specs is available on https://spec.openapis.org/oas/latest.html#response-object
OpenAPIResponses() map[string]map[string]any
// Security requirement object of specific endpoint.
// example :
// func (Doc) OpenAPISecurity() []map[string][]string {
// return []map[string][]string{
// {
// "my_app_auth": {
// "products:get",
// "products:create",
// },
// },
// }
// }
//
// Full specs is available on https://spec.openapis.org/oas/latest.html#security-requirement-object
OpenAPISecurity() []map[string][]string
OpenAPIServer() []map[string]any
OpenAPIOperationID() string
OpenAPICallbacks() map[string]any
OpenAPIDeprecated() bool
// Allows referencing an external resource for extended documentation of specific endpoint
// example :
// func (Doc) OpenAPIExternalDoc() (string, string) {
// return "https://example.com", "Find more info here"
// }
OpenAPIExternalDoc() (string, string)
}
// OpenAPISchemaComponent defines the interface for components with OpenAPI schemas.
type OpenAPISchemaComponent interface {
OpenAPISchemaName() string
GetOpenAPISchema() map[string]any
}
// OpenAPIOperation represents an OpenAPI operation object.
type OpenAPIOperation struct {
ID string
Tags []string
Summary string
Description string
PathParams []map[string]any
HeaderParams []map[string]any
CookieParams []map[string]any
QueryParams []map[string]any
Body map[string]any
Responses map[string]map[string]any
Securities []map[string][]string
Servers []map[string]any
Callbacks map[string]any
IsDeprecated bool
ExternalDocUrl string
ExternalDocDesc string
}
func (o *OpenAPIOperation) OpenAPITags() []string {
return o.Tags
}
func (o *OpenAPIOperation) OpenAPISummary() string {
return o.Summary
}
func (o *OpenAPIOperation) OpenAPIDescription() string {
return o.Description
}
func (o *OpenAPIOperation) OpenAPIPathParam() []map[string]any {
return o.PathParams
}
func (o *OpenAPIOperation) OpenAPIHeaderParam() []map[string]any {
return o.HeaderParams
}
func (o *OpenAPIOperation) OpenAPICookieParam() []map[string]any {
return o.CookieParams
}
func (o *OpenAPIOperation) OpenAPIQueryParam() []map[string]any {
return o.QueryParams
}
func (o *OpenAPIOperation) OpenAPIBody() map[string]any {
return o.Body
}
func (o *OpenAPIOperation) OpenAPIResponses() map[string]map[string]any {
return o.Responses
}
func (o *OpenAPIOperation) OpenAPISecurity() []map[string][]string {
return o.Securities
}
func (o *OpenAPIOperation) OpenAPIOperationID() string {
return o.ID
}
func (o *OpenAPIOperation) OpenAPICallbacks() map[string]any {
return o.Callbacks
}
func (o *OpenAPIOperation) OpenAPIDeprecated() bool {
return o.IsDeprecated
}
func (o *OpenAPIOperation) OpenAPIServer() []map[string]any {
return o.Servers
}
func (o *OpenAPIOperation) OpenAPIExternalDoc() (string, string) {
return o.ExternalDocUrl, o.ExternalDocDesc
}