forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gensvc.go
58 lines (49 loc) · 1.7 KB
/
gensvc.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
package gogen
import (
_ "embed"
"fmt"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
const contextFilename = "service_context"
//go:embed svc.tpl
var contextTemplate string
func genServiceContext(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
filename, err := format.FileNamingFormat(cfg.NamingFormat, contextFilename)
if err != nil {
return err
}
var middlewareStr string
var middlewareAssignment string
middlewares := getMiddleware(api)
for _, item := range middlewares {
middlewareStr += fmt.Sprintf("%s rest.Middleware\n", item)
name := strings.TrimSuffix(item, "Middleware") + "Middleware"
middlewareAssignment += fmt.Sprintf("%s: %s,\n", item,
fmt.Sprintf("middleware.New%s().%s", strings.Title(name), "Handle"))
}
configImport := "\"" + pathx.JoinPackages(rootPkg, configDir) + "\""
if len(middlewareStr) > 0 {
configImport += "\n\t\"" + pathx.JoinPackages(rootPkg, middlewareDir) + "\""
configImport += fmt.Sprintf("\n\t\"%s/rest\"", vars.ProjectOpenSourceURL)
}
return genFile(fileGenConfig{
dir: dir,
subdir: contextDir,
filename: filename + ".go",
templateName: "contextTemplate",
category: category,
templateFile: contextTemplateFile,
builtinTemplate: contextTemplate,
data: map[string]string{
"configImport": configImport,
"config": "config.Config",
"middleware": middlewareStr,
"middlewareAssignment": middlewareAssignment,
},
})
}