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

84 lines
1.8 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package gogen
import (
"bytes"
"fmt"
"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"
2020-10-15 16:36:49 +08:00
"github.com/tal-tech/go-zero/tools/goctl/templatex"
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/vars"
2020-07-29 17:11:41 +08:00
)
const (
contextFilename = "servicecontext.go"
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}
2020-07-29 17:11:41 +08:00
}
`
)
func genServiceContext(dir string, api *spec.ApiSpec) error {
fp, created, err := util.MaybeCreateFile(dir, contextDir, contextFilename)
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 := templatex.LoadTemplate(category, contextTemplateFile, contextTemplate)
if err != nil {
return err
}
var middlewareStr string
for _, item := range getMiddleware(api) {
middlewareStr += fmt.Sprintf("%s rest.Middleware\n", item)
}
2020-08-10 17:26:47 +08:00
var configImport = "\"" + ctlutil.JoinPackages(parentPkg, configDir) + "\""
if len(middlewareStr) > 0 {
configImport += fmt.Sprintf("\n\"%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,
2020-07-29 17:11:41 +08:00
})
if err != nil {
return nil
}
formatCode := formatCode(buffer.String())
_, err = fp.WriteString(formatCode)
return err
}