go-zero/tools/goctl/api/gogen/gensvc.go

81 lines
2.1 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package gogen
import (
"fmt"
"strings"
2020-07-29 17:11:41 +08:00
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/config"
2020-08-10 17:26:47 +08:00
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/format"
"github.com/tal-tech/go-zero/tools/goctl/vars"
2020-07-29 17:11:41 +08:00
)
const (
contextFilename = "service_context"
2020-07-29 17:11:41 +08:00
contextTemplate = `package svc
import (
{{.configImport}}
)
2020-07-29 17:11:41 +08:00
type ServiceContext struct {
Config {{.config}}
{{.middleware}}
2020-07-29 17:11:41 +08:00
}
2020-08-29 20:27:52 +08:00
func NewServiceContext(c {{.config}}) *ServiceContext {
return &ServiceContext{
Config: c,
{{.middlewareAssignment}}
}
}
2020-07-29 17:11:41 +08:00
`
)
func genServiceContext(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
filename, err := format.FileNamingFormat(cfg.NamingFormat, contextFilename)
if err != nil {
return err
}
2021-04-15 19:49:17 +08:00
authNames := getAuths(api)
2020-07-29 17:11:41 +08:00
var auths []string
for _, item := range authNames {
auths = append(auths, fmt.Sprintf("%s config.AuthConfig", item))
}
var middlewareStr string
var middlewareAssignment string
2021-04-15 19:49:17 +08:00
middlewares := getMiddleware(api)
for _, item := range middlewares {
middlewareStr += fmt.Sprintf("%s rest.Middleware\n", item)
name := strings.TrimSuffix(item, "Middleware") + "Middleware"
2021-01-09 00:17:23 +08:00
middlewareAssignment += fmt.Sprintf("%s: %s,\n", item,
fmt.Sprintf("middleware.New%s().%s", strings.Title(name), "Handle"))
}
configImport := "\"" + ctlutil.JoinPackages(rootPkg, configDir) + "\""
if len(middlewareStr) > 0 {
configImport += "\n\t\"" + ctlutil.JoinPackages(rootPkg, middlewareDir) + "\""
2021-02-20 19:50:03 +08:00
configImport += fmt.Sprintf("\n\t\"%s/rest\"", vars.ProjectOpenSourceURL)
}
2021-01-09 00:17:23 +08:00
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,
},
2020-07-29 17:11:41 +08:00
})
}