gensvc.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package generator
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. conf "github.com/tal-tech/go-zero/tools/goctl/config"
  6. "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
  7. "github.com/tal-tech/go-zero/tools/goctl/util"
  8. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  9. )
  10. const svcTemplate = `package svc
  11. import {{.imports}}
  12. type ServiceContext struct {
  13. Config config.Config
  14. }
  15. func NewServiceContext(c config.Config) *ServiceContext {
  16. return &ServiceContext{
  17. Config:c,
  18. }
  19. }
  20. `
  21. func (g *defaultGenerator) GenSvc(ctx DirContext, _ parser.Proto, cfg *conf.Config) error {
  22. dir := ctx.GetSvc()
  23. svcFilename, err := format.FileNamingFormat(cfg.NamingFormat, "service_context")
  24. if err != nil {
  25. return err
  26. }
  27. fileName := filepath.Join(dir.Filename, svcFilename+".go")
  28. text, err := util.LoadTemplate(category, svcTemplateFile, svcTemplate)
  29. if err != nil {
  30. return err
  31. }
  32. return util.With("svc").GoFmt(true).Parse(text).SaveTo(map[string]interface{}{
  33. "imports": fmt.Sprintf(`"%v"`, ctx.GetConfig().Package),
  34. }, fileName, false)
  35. }