-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin.go
176 lines (160 loc) · 4.93 KB
/
gin.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
package main
import (
"google.golang.org/genproto/googleapis/api/annotations"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"net/http"
"regexp"
"strings"
)
const (
contextPkg = protogen.GoImportPath("context")
ginPkg = protogen.GoImportPath("github.com/gin-gonic/gin")
metadataPkg = protogen.GoImportPath("google.golang.org/grpc/metadata")
deprecationComment = "// Deprecated: Do not use."
)
var methodSets = make(map[string]int)
func generateFile(gen *protogen.Plugin, file *protogen.File, omitempty bool) *protogen.GeneratedFile {
if len(file.Services) == 0 {
return nil
}
filename := file.GeneratedFilenamePrefix + "_gin.pb.go"
g := gen.NewGeneratedFile(filename, file.GoImportPath)
g.P("// Code generated by epltools.")
g.P()
g.P("package ", file.GoPackageName)
g.P()
g.P("// ", contextPkg.Ident(""), metadataPkg.Ident(""))
g.P("// ", ginPkg.Ident(""))
g.P()
for _, service := range file.Services {
genService(gen, file, g, service, omitempty)
}
return g
}
func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service, omitempty bool) {
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P("//")
g.P(deprecationComment)
}
// HTTP Server.
sd := &serviceDesc{
ServiceName: service.GoName,
ServiceFullName: string(service.Desc.FullName()),
Metadata: file.Desc.Path(),
}
for _, method := range service.Methods {
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
continue
}
rule, ok := proto.GetExtension(method.Desc.Options(), annotations.E_Http).(*annotations.HttpRule)
if ok && rule != nil {
for _, bind := range rule.AdditionalBindings {
sd.Methods = append(sd.Methods, buildHTTPRule(g, method, bind))
}
sd.Methods = append(sd.Methods, buildHTTPRule(g, method, rule))
} else {
sd.Methods = append(sd.Methods, defaultMethod(g, method))
}
}
if len(sd.Methods) != 0 {
g.P(sd.execute())
}
}
// defaultMethodPath 根据函数名生成 http 路由
// 例如: GetBlogArticles ==> get: /blog/articles
// 如果方法名首个单词不是 http method 映射,那么默认返回 POST
func defaultMethod(g *protogen.GeneratedFile, m *protogen.Method) *methodDesc {
names := strings.Split(toSnakeCase(m.GoName), "_")
var (
paths []string
httpMethod string
path string
)
switch strings.ToUpper(names[0]) {
case http.MethodGet, "FIND", "QUERY", "LIST", "SEARCH":
httpMethod = http.MethodGet
case http.MethodPost, "CREATE":
httpMethod = http.MethodPost
case http.MethodPut, "UPDATE":
httpMethod = http.MethodPut
case http.MethodPatch:
httpMethod = http.MethodPatch
case http.MethodDelete:
httpMethod = http.MethodDelete
default:
httpMethod = "POST"
paths = names
}
if len(paths) > 0 {
path = strings.Join(paths, "/")
}
if len(names) > 1 {
path = strings.Join(names[1:], "/")
}
md := buildMethodDesc(g, m, httpMethod, path)
return md
}
func buildHTTPRule(g *protogen.GeneratedFile, m *protogen.Method, rule *annotations.HttpRule) *methodDesc {
var (
path string
method string
body string
)
switch pattern := rule.Pattern.(type) {
case *annotations.HttpRule_Get:
path = pattern.Get
method = "GET"
case *annotations.HttpRule_Put:
path = pattern.Put
method = "PUT"
case *annotations.HttpRule_Post:
path = pattern.Post
method = "POST"
case *annotations.HttpRule_Delete:
path = pattern.Delete
method = "DELETE"
case *annotations.HttpRule_Patch:
path = pattern.Patch
method = "PATCH"
case *annotations.HttpRule_Custom:
path = pattern.Custom.Path
method = "Any"
}
body = rule.Body
//responseBody = rule.ResponseBody
md := buildMethodDesc(g, m, method, path)
if body == "byte" {
g.QualifiedGoIdent(protogen.GoImportPath("io/ioutil").Ident(""))
g.QualifiedGoIdent(protogen.GoImportPath("google.golang.org/genproto/googleapis/api/httpbody").Ident(""))
md.HasByte = true
}
if body == "file" {
g.QualifiedGoIdent(protogen.GoImportPath("mime/multipart").Ident(""))
md.HasFile = true
}
md.Comment = strings.ReplaceAll(m.Comments.Leading.String(), "\n", "")
return md
}
func buildMethodDesc(g *protogen.GeneratedFile, m *protogen.Method, method, path string) *methodDesc {
defer func() { methodSets[m.GoName]++ }()
md := &methodDesc{
MethodName: m.GoName,
Num: methodSets[m.GoName],
Request: g.QualifiedGoIdent(m.Input.GoIdent),
Reply: g.QualifiedGoIdent(m.Output.GoIdent),
Path: path,
Method: method,
}
md.initPathParams()
return md
}
var matchFirstCap = regexp.MustCompile("([A-Z])([A-Z][a-z])")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
func toSnakeCase(input string) string {
output := matchFirstCap.ReplaceAllString(input, "${1}_${2}")
output = matchAllCap.ReplaceAllString(output, "${1}_${2}")
output = strings.ReplaceAll(output, "-", "_")
return strings.ToLower(output)
}