forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genpacket.go
219 lines (197 loc) · 5.36 KB
/
genpacket.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
package javagen
import (
"bytes"
_ "embed"
"fmt"
"strings"
"text/template"
"github.com/qkbyte/go-zero/core/stringx"
"github.com/qkbyte/go-zero/tools/goctl/api/spec"
apiutil "github.com/qkbyte/go-zero/tools/goctl/api/util"
"github.com/qkbyte/go-zero/tools/goctl/util"
)
//go:embed packet.tpl
var packetTemplate string
func genPacket(dir, packetName string, api *spec.ApiSpec) error {
for _, route := range api.Service.Routes() {
if err := createWith(dir, api, route, packetName); err != nil {
return err
}
}
return nil
}
func createWith(dir string, api *spec.ApiSpec, route spec.Route, packetName string) error {
packet := route.Handler
packet = strings.Replace(packet, "Handler", "Packet", 1)
packet = strings.Title(packet)
if !strings.HasSuffix(packet, "Packet") {
packet += "Packet"
}
javaFile := packet + ".java"
fp, created, err := apiutil.MaybeCreateFile(dir, "", javaFile)
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
hasRequestBody := false
if route.RequestType != nil {
if defineStruct, ok := route.RequestType.(spec.DefineStruct); ok {
hasRequestBody = len(defineStruct.GetBodyMembers()) > 0 || len(defineStruct.GetFormMembers()) > 0
}
}
params := strings.TrimSpace(paramsForRoute(route))
if len(params) > 0 && hasRequestBody {
params += ", "
}
paramsDeclaration := declarationForRoute(route)
paramsSetter := paramsSet(route)
imports := getImports(api, packetName)
if len(route.ResponseTypeName()) == 0 {
imports += fmt.Sprintf("\v%s", "import com.xhb.core.response.EmptyResponse;")
}
t := template.Must(template.New("packetTemplate").Parse(packetTemplate))
var tmplBytes bytes.Buffer
err = t.Execute(&tmplBytes, map[string]interface{}{
"packetName": packet,
"method": strings.ToUpper(route.Method),
"uri": processUri(route),
"responseType": stringx.TakeOne(util.Title(route.ResponseTypeName()), "EmptyResponse"),
"params": params,
"paramsDeclaration": strings.TrimSpace(paramsDeclaration),
"paramsSetter": paramsSetter,
"packet": packetName,
"requestType": util.Title(route.RequestTypeName()),
"HasRequestBody": hasRequestBody,
"imports": imports,
"doc": doc(route),
})
if err != nil {
return err
}
_, err = fp.WriteString(formatSource(tmplBytes.String()))
return err
}
func doc(route spec.Route) string {
comment := route.JoinedDoc()
if len(comment) > 0 {
formatter := `
/*
%s
*/`
return fmt.Sprintf(formatter, comment)
}
return ""
}
func getImports(api *spec.ApiSpec, packetName string) string {
var builder strings.Builder
allTypes := api.Types
if len(allTypes) > 0 {
fmt.Fprintf(&builder, "import com.xhb.logic.http.packet.%s.model.*;\n", packetName)
}
return builder.String()
}
func paramsSet(route spec.Route) string {
path := route.Path
cops := strings.Split(path, "/")
var builder strings.Builder
for _, cop := range cops {
if len(cop) == 0 {
continue
}
if strings.HasPrefix(cop, ":") {
param := cop[1:]
builder.WriteString("\n")
builder.WriteString(fmt.Sprintf("\t\tthis.%s = %s;", param, param))
}
}
result := builder.String()
return result
}
func paramsForRoute(route spec.Route) string {
path := route.Path
cops := strings.Split(path, "/")
var builder strings.Builder
for _, cop := range cops {
if len(cop) == 0 {
continue
}
if strings.HasPrefix(cop, ":") {
builder.WriteString(fmt.Sprintf("String %s, ", cop[1:]))
}
}
return strings.TrimSuffix(builder.String(), ", ")
}
func declarationForRoute(route spec.Route) string {
path := route.Path
cops := strings.Split(path, "/")
var builder strings.Builder
writeIndent(&builder, 1)
for _, cop := range cops {
if len(cop) == 0 {
continue
}
if strings.HasPrefix(cop, ":") {
writeIndent(&builder, 1)
builder.WriteString(fmt.Sprintf("private String %s;\n", cop[1:]))
}
}
result := strings.TrimSpace(builder.String())
if len(result) > 0 {
result = "\n" + result
}
return result
}
func processUri(route spec.Route) string {
path := route.Path
var builder strings.Builder
cops := strings.Split(path, "/")
for index, cop := range cops {
if len(cop) == 0 {
continue
}
if strings.HasPrefix(cop, ":") {
builder.WriteString("/\" + " + cop[1:] + " + \"")
} else {
builder.WriteString("/" + cop)
if index == len(cops)-1 {
builder.WriteString("\"")
}
}
}
result := strings.TrimSuffix(builder.String(), " + \"")
if strings.HasPrefix(result, "/") {
result = strings.TrimPrefix(result, "/")
result = "\"" + result
}
return result + formString(route)
}
func formString(route spec.Route) string {
var keyValues []string
if defineStruct, ok := route.RequestType.(spec.DefineStruct); ok {
forms := defineStruct.GetFormMembers()
for _, item := range forms {
name, err := item.GetPropertyName()
if err != nil {
panic(err)
}
strcat := "?"
if len(keyValues) > 0 {
strcat = "&"
}
if item.Type.Name() == "bool" {
name = strings.TrimPrefix(name, "Is")
name = strings.TrimPrefix(name, "is")
keyValues = append(keyValues, fmt.Sprintf(`"%s%s=" + request.is%s()`, strcat, name, strings.Title(name)))
} else {
keyValues = append(keyValues, fmt.Sprintf(`"%s%s=" + request.get%s()`, strcat, name, strings.Title(name)))
}
}
if len(keyValues) > 0 {
return " + " + strings.Join(keyValues, " + ")
}
}
return ""
}