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

63 lines
1.3 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-08-10 17:26:47 +08:00
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
2020-07-29 17:11:41 +08:00
)
const (
contextFilename = "servicecontext.go"
contextTemplate = `package svc
import {{.configImport}}
type ServiceContext struct {
Config {{.config}}
}
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-08-10 17:26:47 +08:00
var configImport = "\"" + ctlutil.JoinPackages(parentPkg, configDir) + "\""
2020-07-29 17:11:41 +08:00
t := template.Must(template.New("contextTemplate").Parse(contextTemplate))
buffer := new(bytes.Buffer)
err = t.Execute(buffer, map[string]string{
"configImport": configImport,
"config": "config.Config",
})
if err != nil {
return nil
}
formatCode := formatCode(buffer.String())
_, err = fp.WriteString(formatCode)
return err
}