/
apidoc.go
527 lines (479 loc) · 12.3 KB
/
apidoc.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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package miso
import (
"fmt"
"html/template"
"reflect"
"strings"
"sync"
"time"
)
const (
TagApiDocDesc = "desc"
)
var (
ApiDocTypeAlias = map[string]string{
"ETime": "int64",
"*ETime": "int64",
"*miso.ETime": "int64",
}
apiDocTmpl *template.Template
buildApiDocTmplOnce sync.Once
ignoredJsonDocTag = []string{"form", "header"}
)
func init() {
SetDefProp(PropServerGenerateEndpointDocEnabled, true)
}
type ParamDoc struct {
Name string
Desc string
}
type HttpRouteDoc struct {
Url string
Method string
Extra map[string][]any
Desc string // description of the route (metadata).
Scope string // the documented access scope of the route, it maybe "PUBLIC" or something else (metadata).
Resource string // the documented resource that the route should be bound to (metadata).
Headers []ParamDoc // the documented header parameters that will be used by the endpoint (metadata).
QueryParams []ParamDoc // the documented query parameters that will used by the endpoint (metadata).
JsonRequestDesc []jsonDesc // the documented json request type that is expected by the endpoint (metadata).
JsonResponseDesc []jsonDesc // the documented json response type that will be returned by the endpoint (metadata).
Curl string
}
func buildHttpRouteDoc(rail Rail, hr []HttpRoute) []HttpRouteDoc {
docs := make([]HttpRouteDoc, 0, len(hr))
for _, r := range hr {
d := HttpRouteDoc{
Url: r.Url,
Method: r.Method,
Extra: r.Extra,
Desc: r.Desc,
Scope: r.Scope,
Resource: r.Resource,
Headers: r.Headers,
QueryParams: r.QueryParams,
}
if r.JsonRequestVal != nil {
d.JsonRequestDesc = buildJsonDesc(reflect.ValueOf(r.JsonRequestVal))
}
if r.JsonResponseVal != nil {
d.JsonResponseDesc = buildJsonDesc(reflect.ValueOf(r.JsonResponseVal))
}
d.Curl = genRouteCurl(d)
docs = append(docs, d)
}
return docs
}
func genMarkDownDoc(hr []HttpRouteDoc) string {
b := strings.Builder{}
b.WriteString("# API Endpoints\n")
for _, r := range hr {
b.WriteString("\n- ")
b.WriteString(r.Method)
b.WriteString(" ")
b.WriteString(r.Url)
if r.Desc != "" {
b.WriteRune('\n')
b.WriteString(Spaces(2))
b.WriteString("- Description: ")
b.WriteString(r.Desc)
}
if r.Scope != "" {
b.WriteRune('\n')
b.WriteString(Spaces(2))
b.WriteString("- Expected Access Scope: ")
b.WriteString(r.Scope)
}
// if r.Resource != "" {
// b.WriteRune('\n')
// b.WriteString(Spaces(2))
// b.WriteString("- Bound to Resource: \"")
// b.WriteString(r.Resource)
// b.WriteRune('"')
// }
if len(r.Headers) > 0 {
b.WriteRune('\n')
b.WriteString(Spaces(2))
b.WriteString("- Header Parameter:")
for _, h := range r.Headers {
b.WriteRune('\n')
b.WriteString(Spaces(4))
b.WriteString("- \"")
b.WriteString(h.Name)
b.WriteString("\": ")
b.WriteString(h.Desc)
}
}
if len(r.QueryParams) > 0 {
b.WriteRune('\n')
b.WriteString(Spaces(2))
b.WriteString("- Query Parameter:")
for _, q := range r.QueryParams {
b.WriteRune('\n')
b.WriteString(Spaces(4))
b.WriteString("- \"")
b.WriteString(q.Name)
b.WriteString("\": ")
b.WriteString(q.Desc)
}
}
if len(r.JsonRequestDesc) > 0 {
b.WriteRune('\n')
b.WriteString(Spaces(2))
b.WriteString("- JSON Request:")
appendJsonPayloadDoc(&b, r.JsonRequestDesc, 2)
}
if len(r.JsonResponseDesc) > 0 {
b.WriteRune('\n')
b.WriteString(Spaces(2))
b.WriteString("- JSON Response:")
appendJsonPayloadDoc(&b, r.JsonResponseDesc, 2)
}
}
return b.String()
}
func appendJsonPayloadDoc(b *strings.Builder, jds []jsonDesc, indent int) {
for _, jd := range jds {
b.WriteString(fmt.Sprintf("\n%s- \"%s\": (%s) %s", Spaces(indent+2), jd.Name, jd.TypeName, jd.Desc))
if len(jd.Fields) > 0 {
appendJsonPayloadDoc(b, jd.Fields, indent+2)
}
}
}
func buildJsonDesc(v reflect.Value) []jsonDesc {
t := v.Type()
jds := make([]jsonDesc, 0, 5)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if IsVoid(f.Type) {
continue
}
skipped := false
for _, it := range ignoredJsonDocTag {
if v := f.Tag.Get(it); v != "" {
skipped = true
break
}
}
if skipped {
continue
}
var name string
if v := f.Tag.Get("json"); v != "" {
if v == "-" {
continue
}
name = v
} else {
name = LowercaseNamingStrategy(f.Name)
}
typeName := TypeName(f.Type)
typeAlias, typeAliasMatched := ApiDocTypeAlias[typeName]
if typeAliasMatched {
typeName = typeAlias
}
jd := jsonDesc{
Name: name,
TypeName: typeName,
Desc: f.Tag.Get(TagApiDocDesc),
Fields: []jsonDesc{},
}
if typeAliasMatched {
jds = append(jds, jd)
continue
}
fv := v.Field(i)
appendable := true
if f.Type.Kind() == reflect.Interface {
if !fv.IsZero() && !fv.IsNil() {
if ele := fv.Elem(); ele.IsValid() {
et := ele.Type()
jd.TypeName = TypeName(et)
jd.Fields = reflectAppendJsonDesc(et, ele, jd.Fields)
}
} else {
appendable = false // e.g., the any field in GnResp[any]{}
Debugf("reflect.Value is zero or nil, not displayed in api doc, type: %v, field: %v", t.Name(), jd.Name)
}
} else {
jd.Fields = reflectAppendJsonDesc(f.Type, fv, jd.Fields)
}
if appendable {
jds = append(jds, jd)
}
}
return jds
}
func reflectAppendJsonDesc(t reflect.Type, v reflect.Value, fields []jsonDesc) []jsonDesc {
if t.Kind() == reflect.Struct {
fields = append(fields, buildJsonDesc(v)...)
} else if t.Kind() == reflect.Slice {
et := t.Elem()
if et.Kind() == reflect.Struct {
ev := reflect.New(et).Elem()
fields = append(fields, buildJsonDesc(ev)...)
}
} else if t.Kind() == reflect.Pointer {
ev := reflect.New(t.Elem()).Elem()
if ev.Kind() == reflect.Struct {
fields = append(fields, buildJsonDesc(ev)...)
}
} else if t.Kind() == reflect.Interface {
if !v.IsZero() && !v.IsNil() {
if ele := v.Elem(); ele.IsValid() {
et := ele.Type()
fields = reflectAppendJsonDesc(et, ele, fields)
}
}
}
return fields
}
type jsonDesc struct {
Name string
TypeName string
Desc string
Fields []jsonDesc
}
func serveApiDocTmpl(rail Rail) error {
var err error
buildApiDocTmplOnce.Do(func() {
t, er := template.New("").Parse(`
{{define "unpackJsonDesc"}}
<ul>
{{range . }}
<li>'{{.Name}}': <i>({{.TypeName}})</i> {{.Desc}}
{{if .Fields}}
{{template "unpackJsonDesc" .Fields}}
{{end}}
</li>
{{end}}
</ul>
{{end}}
{{define "apiDocTempl"}}
<div style="margin:30px;">
<h1>Generated {{.App}} API Documentation:</h1>
<h2>1. HTML API DOC:</h2>
{{range .Doc}}
<div style="background-color:DBD5D4; margin-top:30px; margin-bottom:30px;
padding-left:30px; padding-right:30px; padding-top:10px; padding-bottom:10px; border-radius: 20px;">
<h3>{{.Method}} {{.Url}}</h3>
{{if .Desc }}
<p>
<div style="text-indent:8px;border-left: 4px solid #757575;">
<b><i>Description:</i></b>
</div>
</p>
<p> {{.Desc}}</p>
{{end}}
{{if .Scope }}
<p>
<div style="text-indent:8px;border-left: 4px solid #757575;">
<b><i>Expected Access Scope:</i></b>
</div>
</p>
<p> {{.Scope}}</p>
{{end}}
{{if .Headers}}
<p>
<div style="text-indent:8px;border-left: 4px solid #757575;">
<b><i>Header Parameters:</i></b>
</div>
<ul>
{{range .Headers}}
<li>'{{.Name}}': {{.Desc}}</li>
{{end}}
</ul>
</p>
{{end}}
{{if .QueryParams}}
<p>
<div style="text-indent:8px;border-left: 4px solid #757575;">
<b><i>Query Parameters:</i></b>
</div>
<ul>
{{range .QueryParams}}
<li>'{{.Name}}': {{.Desc}}</li>
{{end}}
</ul>
</p>
{{end}}
{{if .JsonRequestDesc}}
<p>
<div style="text-indent:8px;border-left: 4px solid #757575;">
<b><i>JSON Request:</i></b>
</div>
{{template "unpackJsonDesc" .JsonRequestDesc}}
</p>
{{end}}
{{if .JsonResponseDesc}}
<p>
<div style="text-indent:8px;border-left: 4px solid #757575;">
<b><i>JSON Response:</i></b>
</div>
{{template "unpackJsonDesc" .JsonResponseDesc}}
</p>
{{end}}
{{if .Curl}}
<p>
<div style="text-indent:8px;border-left: 4px solid #757575;">
<b><i>cURL:</i></b>
</div>
<p><pre>{{.Curl}}</pre></p>
</p>
{{end}}
</div>
{{end}}
<h2>2. Markdown API Doc:</h2>
<div style="text-align: right;">
<button style="padding:10px; box-shadow: 3px 3px 10px lightgrey;" onclick="copyMarkdown()">Copy Generated Markdown</button>
</div>
<pre id="markdownPre" style="white-space: pre-wrap; background-color:DBD5D4; padding:30px; border-radius: 30px;">{{.Markdown}}</pre>
<script>
function copyMarkdown() {
var preContent = document.getElementById("markdownPre").textContent;
const textArea = document.createElement('textarea');
textArea.textContent = preContent;
document.body.append(textArea);
textArea.select();
document.execCommand("copy");
textArea.remove();
}
</script>
</div>
{{end}}
`)
if er != nil {
err = er
return
}
apiDocTmpl = t
})
if err != nil {
return err
}
RawGet("/doc/api",
func(inb *Inbound) {
defer DebugTimeOp(rail, time.Now(), "gen api doc")
routeDoc := buildHttpRouteDoc(rail, GetHttpRoutes())
markdown := genMarkDownDoc(routeDoc)
w, _ := inb.Unwrap()
if err := apiDocTmpl.ExecuteTemplate(w, "apiDocTempl",
struct {
App string
Doc []HttpRouteDoc
Markdown string
}{
App: GetPropStr(PropAppName),
Doc: routeDoc,
Markdown: markdown,
}); err != nil {
rail.Errorf("failed to serve apiDocTmpl, %v", err)
}
}).
Desc("Serve the generated API documentation webpage").
Public()
rail.Infof("Exposing API Documentation on http://localhost:%v/doc/api", GetPropInt(PropServerPort))
return nil
}
func parseQueryDoc(t reflect.Type) []ParamDoc {
if t == nil {
return nil
}
pds := []ParamDoc{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if IsVoid(f.Type) {
continue
}
query := f.Tag.Get(TagQueryParam)
if query == "" {
continue
}
desc := f.Tag.Get(TagApiDocDesc)
pds = append(pds, ParamDoc{
Name: query,
Desc: desc,
})
}
return pds
}
func parseHeaderDoc(t reflect.Type) []ParamDoc {
if t == nil {
return nil
}
pds := []ParamDoc{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if IsVoid(f.Type) {
continue
}
header := f.Tag.Get(TagHeaderParam)
if header == "" {
continue
}
header = strings.ToLower(header)
desc := f.Tag.Get(TagApiDocDesc)
pds = append(pds, ParamDoc{
Name: header,
Desc: desc,
})
}
return pds
}
func genRouteCurl(d HttpRouteDoc) string {
sl := new(SLPinter)
sl.LineSuffix = " \\"
var qp string
for i, q := range d.QueryParams {
if qp == "" {
qp = "?"
}
qp += fmt.Sprintf("%s=%s", q.Name, "apple")
if i < len(d.QueryParams)-1 {
qp += "&"
}
}
sl.Printlnf("curl -X %s 'http://localhost:%s%s%s'", d.Method, GetPropStr(PropServerPort), d.Url, qp)
sl.LinePrefix = " "
for _, h := range d.Headers {
sl.Printlnf("-H '%s: apple'", h.Name)
}
if len(d.JsonRequestDesc) > 0 {
sl.Printlnf("-H 'Content-Type: application/json'")
jm := map[string]any{}
genJsonReqDemo(jm, d.JsonRequestDesc)
sj, err := SWriteJson(jm)
if err == nil {
sl.Printlnf("-d '%s'", sj)
}
// sl.Printlnf("-d '{ }'")
}
return sl.String()
}
func genJsonReqDemo(jm map[string]any, descs []jsonDesc) {
for _, d := range descs {
if len(d.Fields) > 0 {
t := map[string]any{}
genJsonReqDemo(t, d.Fields)
jm[d.Name] = t
} else {
var v any
switch d.TypeName {
case "string", "*string":
v = ""
case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64",
"*int", "*int8", "*int16", "*int32", "*int64", "*uint", "*uint8", "*uint16", "*uint32", "*uint64":
v = 0
case "float32", "float64", "*float32", "*float64":
v = 0.0
case "bool", "*bool":
v = false
default:
if strings.HasPrefix(d.TypeName, "[]") {
v = make([]any, 0)
}
}
jm[d.Name] = v
}
}
}