gensvc.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. // GenSvc generates the servicecontext.go file, which is the resource dependency of a service,
  22. // such as rpc dependency, model dependency, etc.
  23. func (g *DefaultGenerator) GenSvc(ctx DirContext, _ parser.Proto, cfg *conf.Config) error {
  24. dir := ctx.GetSvc()
  25. svcFilename, err := format.FileNamingFormat(cfg.NamingFormat, "service_context")
  26. if err != nil {
  27. return err
  28. }
  29. fileName := filepath.Join(dir.Filename, svcFilename+".go")
  30. text, err := util.LoadTemplate(category, svcTemplateFile, svcTemplate)
  31. if err != nil {
  32. return err
  33. }
  34. return util.With("svc").GoFmt(true).Parse(text).SaveTo(map[string]interface{}{
  35. "imports": fmt.Sprintf(`"%v"`, ctx.GetConfig().Package),
  36. }, fileName, false)
  37. }