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.
go-zero/tools/goctl/api/gogen/genmain.go

99 lines
2.4 KiB
Go

4 years ago
package gogen
import (
"bytes"
"fmt"
"strings"
"text/template"
"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"
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"
4 years ago
)
const mainTemplate = `package main
import (
"flag"
"fmt"
4 years ago
{{.importPackages}}
)
var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
4 years ago
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
4 years ago
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
4 years ago
}
`
func genMain(dir string, cfg *config.Config, api *spec.ApiSpec) error {
4 years ago
name := strings.ToLower(api.Service.Name)
if strings.HasSuffix(name, "-api") {
name = strings.ReplaceAll(name, "-api", "")
}
filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
if err != nil {
return err
}
goFile := filename + ".go"
4 years ago
fp, created, err := util.MaybeCreateFile(dir, "", goFile)
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
parentPkg, err := getParentPackage(dir)
if err != nil {
return err
}
text, err := ctlutil.LoadTemplate(category, mainTemplateFile, mainTemplate)
if err != nil {
return err
}
t := template.Must(template.New("mainTemplate").Parse(text))
4 years ago
buffer := new(bytes.Buffer)
err = t.Execute(buffer, map[string]string{
"importPackages": genMainImports(parentPkg),
"serviceName": api.Service.Name,
})
if err != nil {
return err
4 years ago
}
4 years ago
formatCode := formatCode(buffer.String())
_, err = fp.WriteString(formatCode)
return err
}
func genMainImports(parentPkg string) string {
var imports []string
imports = append(imports, fmt.Sprintf("\"%s\"", ctlutil.JoinPackages(parentPkg, configDir)))
imports = append(imports, fmt.Sprintf("\"%s\"", ctlutil.JoinPackages(parentPkg, handlerDir)))
imports = append(imports, fmt.Sprintf("\"%s\"\n", ctlutil.JoinPackages(parentPkg, contextDir)))
imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceUrl))
imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceUrl))
4 years ago
return strings.Join(imports, "\n\t")
}