-
Notifications
You must be signed in to change notification settings - Fork 3
/
route.go
117 lines (103 loc) · 2.43 KB
/
route.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
package eapi
import (
"go/ast"
"net/http"
"strings"
"github.com/gotomicro/eapi/annotation"
"github.com/gotomicro/eapi/spec"
)
type RouteGroup struct {
Prefix string
}
type API struct {
Method string
FullPath string
Spec *APISpec
}
func NewAPI(method string, fullPath string) *API {
return &API{
Method: method,
FullPath: fullPath,
Spec: NewAPISpec(),
}
}
func (r *API) applyToPathItem(pathItem *spec.PathItem) {
switch r.Method {
case http.MethodGet:
pathItem.Get = r.Operation()
case http.MethodHead:
pathItem.Head = r.Operation()
case http.MethodPost:
pathItem.Post = r.Operation()
case http.MethodPut:
pathItem.Put = r.Operation()
case http.MethodPatch:
pathItem.Patch = r.Operation()
case http.MethodDelete:
pathItem.Delete = r.Operation()
case http.MethodOptions:
pathItem.Options = r.Operation()
case http.MethodTrace:
pathItem.Trace = r.Operation()
}
}
func (r *API) Operation() *spec.Operation {
return r.Spec.Operation
}
type APIs []*API
func (r *APIs) add(items ...*API) {
*r = append(*r, items...)
}
type APISpec struct {
Consumes []string
*spec.Operation
}
func NewAPISpec() *APISpec {
op := spec.NewOperation()
op.Responses = spec.NewResponses()
delete(op.Responses, "default")
return &APISpec{
Operation: op,
}
}
// LoadFromFuncDecl load annotations/description from comments of handler function
func (s *APISpec) LoadFromFuncDecl(ctx *Context, funcDecl *ast.FuncDecl) {
cg := funcDecl.Doc
comment := ParseComment(cg, ctx.Package().Fset)
s.LoadFromComment(ctx, comment)
if s.Description == "" {
// 使用注释里的普通文本作为描述
s.Description = strings.TrimSpace(strings.TrimPrefix(comment.Text(), funcDecl.Name.Name))
}
}
func (s *APISpec) LoadFromComment(ctx *Context, comment *Comment) {
if comment != nil {
if s.Description == "" {
s.Description = comment.Text()
}
if s.Summary == "" {
s.Summary = comment.Summary()
}
if len(s.Tags) == 0 {
s.Tags = comment.Tags()
}
if s.OperationID == "" {
s.OperationID = comment.ID()
}
if len(s.Consumes) == 0 {
s.Consumes = append(s.Consumes, comment.Consumes()...)
}
if !s.Deprecated {
comment.Deprecated()
}
if s.Security == nil {
s.Security = comment.Security()
}
}
if len(s.Tags) == 0 {
s.Tags = ctx.CommentStack().LookupTags()
}
if s.Security == nil {
s.Security = convertSecAnnotationToSecurityRequirements(ctx.CommentStack().LookupAnnotations(annotation.Security))
}
}