-
Notifications
You must be signed in to change notification settings - Fork 98
/
grpc-http-pb.go
326 lines (295 loc) · 11 KB
/
grpc-http-pb.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package generate
import (
"errors"
"fmt"
"github.com/huandu/xstrings"
"github.com/spf13/cobra"
"github.com/zhufuyi/sponge/pkg/replacer"
)
// GRPCAndHTTPPbCommand generate grpc+http service code bash on protobuf file
func GRPCAndHTTPPbCommand() *cobra.Command {
var (
moduleName string // module name for go.mod
serverName string // server name
projectName string // project name for deployment name
repoAddr string // image repo address
outPath string // output directory
protobufFile string // protobuf file, support * matching
suitedMonoRepo bool // whether the generated code is suitable for mono-repo
)
cmd := &cobra.Command{
Use: "grpc-http-pb",
Short: "Generate grpc+http service code based on protobuf file",
Long: `generate grpc+http service code based on protobuf file.
Examples:
# generate grpc service code.
sponge micro grpc-http-pb --module-name=yourModuleName --server-name=yourServerName --project-name=yourProjectName --protobuf-file=./demo.proto
# generate grpc service code and specify the output directory, Note: code generation will be canceled when the latest generated file already exists.
sponge micro grpc-http-pb --module-name=yourModuleName --server-name=yourServerName --project-name=yourProjectName --protobuf-file=./demo.proto --out=./yourServerDir
# generate grpc service code and specify the docker image repository address.
sponge micro grpc-http-pb --module-name=yourModuleName --server-name=yourServerName --project-name=yourProjectName --repo-addr=192.168.3.37:9443/user-name --protobuf-file=./demo.proto
# if you want the generated code to suited to mono-repo, you need to specify the parameter --suited-mono-repo=true
`,
SilenceErrors: true,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
var err error
projectName, serverName, err = convertProjectAndServerName(projectName, serverName)
if err != nil {
return err
}
if suitedMonoRepo {
outPath = changeOutPath(outPath, serverName)
}
g := &httpAndGRPCPbGenerator{
moduleName: moduleName,
serverName: serverName,
projectName: projectName,
protobufFile: protobufFile,
repoAddr: repoAddr,
outPath: outPath,
suitedMonoRepo: suitedMonoRepo,
}
err = g.generateCode()
if err != nil {
return err
}
_ = generateConfigmap(serverName, outPath)
return nil
},
}
cmd.Flags().StringVarP(&moduleName, "module-name", "m", "", "module-name is the name of the module in the go.mod file")
_ = cmd.MarkFlagRequired("module-name")
cmd.Flags().StringVarP(&serverName, "server-name", "s", "", "server name")
_ = cmd.MarkFlagRequired("server-name")
cmd.Flags().StringVarP(&projectName, "project-name", "p", "", "project name")
_ = cmd.MarkFlagRequired("project-name")
cmd.Flags().StringVarP(&protobufFile, "protobuf-file", "f", "", "proto file")
_ = cmd.MarkFlagRequired("protobuf-file")
cmd.Flags().BoolVarP(&suitedMonoRepo, "suited-mono-repo", "l", false, "whether the generated code is suitable for mono-repo")
cmd.Flags().StringVarP(&repoAddr, "repo-addr", "r", "", "docker image repository address, excluding http and repository names")
cmd.Flags().StringVarP(&outPath, "out", "o", "", "output directory, default is ./serverName_grpc-http-pb_<time>")
return cmd
}
type httpAndGRPCPbGenerator struct {
moduleName string
serverName string
projectName string
protobufFile string
repoAddr string
outPath string
suitedMonoRepo bool
}
// nolint
func (g *httpAndGRPCPbGenerator) generateCode() error {
protobufFiles, isImportTypes, err := parseProtobufFiles(g.protobufFile)
if err != nil {
return err
}
subTplName := "grpc-http-pb"
r := Replacers[TplNameSponge]
if r == nil {
return errors.New("replacer is nil")
}
// setting up template information
subDirs := []string{ // processing-only subdirectories
"api/types", "cmd/serverNameExample_grpcHttpPbExample",
"sponge/configs", "sponge/deployments", "sponge/docs", "sponge/scripts", "sponge/third_party",
"internal/config", "internal/ecode", "internal/server", "internal/service", "internal/routers",
}
subFiles := []string{ // processing of sub-documents only
"sponge/.gitignore", "sponge/.golangci.yml", "sponge/go.mod", "sponge/go.sum",
"sponge/Jenkinsfile", "sponge/Makefile", "sponge/README.md",
}
if g.suitedMonoRepo {
subFiles = removeElements(subFiles, "sponge/go.mod", "sponge/go.sum")
}
ignoreDirs := []string{"cmd/sponge"} // specify the directory in the subdirectory where processing is ignored
ignoreFiles := []string{ // specify the files in the subdirectory to be ignored for processing
"types.pb.validate.go", "types.pb.go", // api/types
"swagger.json", "swagger.yaml", "apis.swagger.json", "apis.html", "docs.go", // sponge/docs
"userExample_http.go", "userExample_rpc.go", // internal/ecode
"routers_pbExample_test.go", "routers.go", "routers_test.go", "userExample.go", "userExample_router.go", // internal/routers
"grpc_test.go", "http_test.go", // internal/server
"userExample.go", "userExample_client_test.go", "userExample_logic.go", "userExample_logic_test.go", "userExample_test.go", "userExample.go.mgo", "userExample_client_test.go.mgo", // internal/service
}
if !isImportTypes {
ignoreFiles = append(ignoreFiles, "types.proto")
}
r.SetSubDirsAndFiles(subDirs, subFiles...)
r.SetIgnoreSubDirs(ignoreDirs...)
r.SetIgnoreSubFiles(ignoreFiles...)
_ = r.SetOutputDir(g.outPath, g.serverName+"_"+subTplName)
fields := g.addFields(r)
r.SetReplacementFields(fields)
if err = r.SaveFiles(); err != nil {
return err
}
_ = saveProtobufFiles(g.moduleName, g.serverName, r.GetOutputDir(), protobufFiles)
_ = saveGenInfo(g.moduleName, g.serverName, g.suitedMonoRepo, r.GetOutputDir())
fmt.Printf(`
using help:
1. open a terminal and execute the command to generate code: make proto
2. open file internal/handler/xxx.go and internal/service/xxx.go, replace panic("implement me") according to template code example.
3. compile and run service: make run
4. visit http://localhost:8080/apis/swagger/index.html in your browser, and test the http api.
open the file "internal/service/xxx_client_test.go" using Goland or VS Code, and test the grpc api.
`)
fmt.Printf("generate %s's grpc+http service code successfully, out = %s\n", g.serverName, r.GetOutputDir())
return nil
}
func (g *httpAndGRPCPbGenerator) addFields(r replacer.Replacer) []replacer.Field {
var fields []replacer.Field
repoHost, _ := parseImageRepoAddr(g.repoAddr)
fields = append(fields, deleteFieldsMark(r, httpFile, startMark, endMark)...)
fields = append(fields, deleteFieldsMark(r, dockerFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteFieldsMark(r, dockerFileBuild, wellStartMark, wellEndMark)...)
fields = append(fields, deleteFieldsMark(r, dockerComposeFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteFieldsMark(r, k8sDeploymentFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteFieldsMark(r, k8sServiceFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteFieldsMark(r, imageBuildFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteFieldsMark(r, imageBuildLocalFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteAllFieldsMark(r, makeFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteFieldsMark(r, gitIgnoreFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteAllFieldsMark(r, protoShellFile, wellStartMark, wellEndMark)...)
fields = append(fields, deleteAllFieldsMark(r, appConfigFile, wellStartMark, wellEndMark)...)
//fields = append(fields, deleteFieldsMark(r, deploymentConfigFile, wellStartMark, wellEndMark)...)
fields = append(fields, replaceFileContentMark(r, readmeFile, "## "+g.serverName)...)
fields = append(fields, []replacer.Field{
{ // replace the configuration of the *.yml file
Old: appConfigFileMark,
New: grpcAndHTTPServerConfigCode,
},
{ // replace the configuration of the *.yml file
Old: appConfigFileMark2,
New: getDBConfigCode(undeterminedDBDriver),
},
//{ // replace the contents of the model/init.go file
// Old: modelInitDBFileMark,
// New: getInitDBCode(DBDriverMysql), // default is mysql
//},
{ // replace the contents of the Dockerfile file
Old: dockerFileMark,
New: dockerFileGrpcCode,
},
{ // replace the contents of the Dockerfile_build file
Old: dockerFileBuildMark,
New: dockerFileBuildGrpcCode,
},
{ // replace the contents of the image-build.sh file
Old: imageBuildFileMark,
New: imageBuildFileGrpcCode,
},
{ // replace the contents of the image-build-local.sh file
Old: imageBuildLocalFileMark,
New: imageBuildLocalFileGrpcCode,
},
{ // replace the contents of the docker-compose.yml file
Old: dockerComposeFileMark,
New: dockerComposeFileGrpcCode,
},
//{ // replace the contents of the *-configmap.yml file
// Old: deploymentConfigFileMark,
// New: getDBConfigCode(DBDriverMysql, true),
//},
{ // replace the contents of the *-deployment.yml file
Old: k8sDeploymentFileMark,
New: k8sDeploymentFileGrpcCode,
},
{ // replace the contents of the *-svc.yml file
Old: k8sServiceFileMark,
New: k8sServiceFileGrpcCode,
},
{ // replace the contents of the proto.sh file
Old: protoShellFileGRPCMark,
New: protoShellGRPCMark,
},
{ // replace the contents of the proto.sh file
Old: protoShellFileMark,
New: protoShellServiceAndHandlerCode,
},
{
Old: "github.com/zhufuyi/sponge",
New: g.moduleName,
},
{
Old: g.moduleName + "/pkg",
New: "github.com/zhufuyi/sponge/pkg",
},
{ // replace the sponge version of the go.mod file
Old: spongeTemplateVersionMark,
New: getLocalSpongeTemplateVersion(),
},
{
Old: "sponge api docs",
New: g.serverName + " api docs",
},
{
Old: "go 1.19",
New: "go 1.20",
},
{
Old: "serverNameExample",
New: g.serverName,
},
// docker image and k8s deployment script replacement
{
Old: "server-name-example",
New: xstrings.ToKebabCase(g.serverName), // snake_case to kebab_case
},
// docker image and k8s deployment script replacement
{
Old: "project-name-example",
New: g.projectName,
},
{
Old: "projectNameExample",
New: g.projectName,
},
{
Old: "repo-addr-example",
New: g.repoAddr,
},
{
Old: "image-repo-host",
New: repoHost,
},
{
Old: "_httpPbExample",
New: "",
},
{
Old: "_grpcHttpPbExample",
New: "",
},
{
Old: "_grpcPbExample",
New: "",
},
{
Old: "_mixExample",
New: "",
},
{
Old: "_pbExample",
New: "",
},
{
Old: "prof.Register(r, prof.WithIOWaitTime())",
New: "// implemented on port 8283",
},
{
Old: `"github.com/zhufuyi/sponge/pkg/gin/prof"`,
New: "",
},
{
Old: "reference-db-config-url",
New: "Reference: https://github.com/zhufuyi/sponge/blob/main/configs/serverNameExample.yml#L87",
},
}...)
if g.suitedMonoRepo {
fs := serverCodeFields(r.GetOutputDir(), g.moduleName, g.serverName)
fields = append(fields, fs...)
}
return fields
}