You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
2.4 KiB
Go
102 lines
2.4 KiB
Go
package gogen
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"text/template"
|
|
|
|
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
|
|
"github.com/tal-tech/go-zero/tools/goctl/api/util"
|
|
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
|
|
"github.com/tal-tech/go-zero/tools/goctl/vars"
|
|
)
|
|
|
|
const (
|
|
contextFilename = "servicecontext.go"
|
|
contextTemplate = `package svc
|
|
|
|
import (
|
|
{{.configImport}}
|
|
)
|
|
|
|
type ServiceContext struct {
|
|
Config {{.config}}
|
|
{{.middleware}}
|
|
}
|
|
|
|
func NewServiceContext(c {{.config}}) *ServiceContext {
|
|
return &ServiceContext{
|
|
Config: c,
|
|
{{.middlewareAssignment}}
|
|
}
|
|
}
|
|
|
|
{{.middlewareImplement}}
|
|
`
|
|
middlewareImplementCode = `func %s(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// TODO generate middleware implement function, delete after code implementation
|
|
}
|
|
}
|
|
|
|
`
|
|
)
|
|
|
|
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
|
|
}
|
|
|
|
text, err := ctlutil.LoadTemplate(category, contextTemplateFile, contextTemplate)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var middlewareStr string
|
|
var middlewareAssignment string
|
|
var middlewareImplement string
|
|
for _, item := range getMiddleware(api) {
|
|
middlewareStr += fmt.Sprintf("%s rest.Middleware\n", item)
|
|
middlewareAssignment += fmt.Sprintf("%s: %s,\n", item, item)
|
|
middlewareImplement += fmt.Sprintf(middlewareImplementCode, item)
|
|
}
|
|
|
|
var configImport = "\"" + ctlutil.JoinPackages(parentPkg, configDir) + "\""
|
|
if len(middlewareStr) > 0 {
|
|
configImport += "\n\t\"net/http\""
|
|
configImport += fmt.Sprintf("\n\t\"%s/rest\"", vars.ProjectOpenSourceUrl)
|
|
}
|
|
|
|
t := template.Must(template.New("contextTemplate").Parse(text))
|
|
buffer := new(bytes.Buffer)
|
|
err = t.Execute(buffer, map[string]string{
|
|
"configImport": configImport,
|
|
"config": "config.Config",
|
|
"middleware": middlewareStr,
|
|
"middlewareAssignment": middlewareAssignment,
|
|
"middlewareImplement": middlewareImplement,
|
|
})
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
formatCode := formatCode(buffer.String())
|
|
_, err = fp.WriteString(formatCode)
|
|
return err
|
|
}
|