/
collector.go
96 lines (76 loc) · 2.45 KB
/
collector.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
package autodoc
import (
"strings"
"github.com/labstack/echo"
"io/ioutil"
"os"
"runtime"
log "github.com/sirupsen/logrus"
)
type apiCollector struct {
prefix string
group *echo.Group
}
// handler_test.go 中调用
func NewAPICollector() *apiCollector {
return &apiCollector{"", echo.New().Group("")}
}
func (g *apiCollector) Group(prefix string, middleware ...echo.MiddlewareFunc) GroupInterface {
return &apiCollector{g.prefix + prefix, g.group.Group(prefix, middleware...)}
}
func (g *apiCollector) Use(middleware ...echo.MiddlewareFunc) {
g.group.Use(middleware...)
}
func getRealHandlerName(name string) string {
const _suffix = ")-fm"
if strings.HasSuffix(name, _suffix) {
splits := strings.Split(name, ".")
last := splits[len(splits)-1]
name = last[:len(last)-len(_suffix)]
}
return name
}
func (g *apiCollector) collect(r *echo.Route, h echo.HandlerFunc) {
_, filePath, lineno, _ := runtime.Caller(2) // skip 的值取决于这行代码离要提取的注释相隔几层调用
comments := readAboveComments(filePath, lineno-1)
// 如果任意一行包含 [skip gen] 则忽略
if in(SkipGen, comments) {
return
}
log.Infoln("处理", r.Method, r.Path)
docGen.add(getRealHandlerName(r.Name), r.Method, r.Path)
if len(comments) > 0 {
docGen.currentAPI().title = comments[0]
docGen.currentAPI().description = strings.Join(comments[1:], "\n")
}
docGen.currentAPI().responseParams = globalResponseJSONParams
h(docGen)
}
// TODO: run middleware?
// 考虑到不同的 GET/POST 可能会调到同一个 handler,在 GET/POST 处提取注释是最准确的
func (g *apiCollector) GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route {
r := g.group.GET(path, h, m...)
g.collect(r, h)
return r
}
func (g *apiCollector) POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route {
r := g.group.POST(path, h, m...)
g.collect(r, h)
return r
}
func (g *apiCollector) PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route {
r := g.group.PUT(path, h, m...)
g.collect(r, h)
return r
}
func (g *apiCollector) DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route {
r := g.group.DELETE(path, h, m...)
g.collect(r, h)
return r
}
func (g *apiCollector) GenerateMarkdown() string {
return docGen.generateMarkdown()
}
func (g *apiCollector) GenerateMarkdownToFile(filePath string) error {
return ioutil.WriteFile(filePath, []byte(g.GenerateMarkdown()), os.ModePerm)
}