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

103 lines
2.4 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package gogen
import (
"bytes"
"fmt"
"strings"
2020-07-29 17:11:41 +08:00
"text/template"
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/api/util"
"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 string, cfg *config.Config, api *spec.ApiSpec) error {
filename, err := format.FileNamingFormat(cfg.NamingFormat, contextFilename)
if err != nil {
return err
}
fp, created, err := util.MaybeCreateFile(dir, contextDir, filename+".go")
2020-07-29 17:11:41 +08:00
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
var authNames = getAuths(api)
var auths []string
for _, item := range authNames {
auths = append(auths, fmt.Sprintf("%s config.AuthConfig", item))
}
parentPkg, err := getParentPackage(dir)
if err != nil {
return err
}
2020-10-15 16:36:49 +08:00
text, err := ctlutil.LoadTemplate(category, contextTemplateFile, contextTemplate)
2020-10-15 16:36:49 +08:00
if err != nil {
return err
}
var middlewareStr string
var middlewareAssignment string
var 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"))
}
2020-08-10 17:26:47 +08:00
var configImport = "\"" + ctlutil.JoinPackages(parentPkg, configDir) + "\""
if len(middlewareStr) > 0 {
configImport += "\n\t\"" + ctlutil.JoinPackages(parentPkg, middlewareDir) + "\""
configImport += fmt.Sprintf("\n\t\"%s/rest\"", vars.ProjectOpenSourceUrl)
}
2020-10-15 16:36:49 +08:00
t := template.Must(template.New("contextTemplate").Parse(text))
2020-07-29 17:11:41 +08:00
buffer := new(bytes.Buffer)
err = t.Execute(buffer, map[string]string{
"configImport": configImport,
"config": "config.Config",
"middleware": middlewareStr,
"middlewareAssignment": middlewareAssignment,
2020-07-29 17:11:41 +08:00
})
if err != nil {
return err
2020-07-29 17:11:41 +08:00
}
2020-07-29 17:11:41 +08:00
formatCode := formatCode(buffer.String())
_, err = fp.WriteString(formatCode)
return err
}