forked from micheartin/docgen-yes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocgen.go
69 lines (57 loc) · 1.47 KB
/
docgen.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
// Package docgen generates the Chi routes documentation in JSON or Markdown.
package docgen
import (
"encoding/json"
"fmt"
"log"
"github.com/go-chi/chi/v5"
)
type Doc struct {
Router DocRouter `json:"router"`
}
type DocRouter struct {
Middlewares []DocMiddleware `json:"middlewares"`
Routes DocRoutes `json:"routes"`
}
type DocMiddleware struct {
FuncInfo
}
type DocRoute struct {
Pattern string `json:"-"`
Handlers DocHandlers `json:"handlers,omitempty"`
Router *DocRouter `json:"router,omitempty"`
}
type DocRoutes map[string]DocRoute // Pattern : DocRoute
type DocHandler struct {
Middlewares []DocMiddleware `json:"middlewares"`
Method string `json:"method"`
FuncInfo
}
type DocHandlers map[string]DocHandler // Method : DocHandler
func PrintRoutes(r chi.Routes) {
var printRoutes func(parentPattern string, r chi.Routes)
printRoutes = func(parentPattern string, r chi.Routes) {
rts := r.Routes()
for _, rt := range rts {
if rt.SubRoutes == nil {
fmt.Println(parentPattern + rt.Pattern)
} else {
pat := rt.Pattern
subRoutes := rt.SubRoutes
printRoutes(parentPattern+pat, subRoutes)
}
}
}
printRoutes("", r)
}
func JSONRoutesDoc(r chi.Routes) string {
return string(JSONRoutesBytes(r))
}
func JSONRoutesBytes(r chi.Routes) []byte {
doc, _ := BuildDoc(r)
b, err := json.MarshalIndent(doc, "", " ")
if err != nil {
log.Panicf("docgen: json.MarshalIndent err: %q input: %+v", err, doc)
}
return b
}