gensvc.go 1.2 KB

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