gensvc.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package gogen
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  6. "github.com/tal-tech/go-zero/tools/goctl/config"
  7. ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  8. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  9. "github.com/tal-tech/go-zero/tools/goctl/vars"
  10. )
  11. const (
  12. contextFilename = "service_context"
  13. contextTemplate = `package svc
  14. import (
  15. {{.configImport}}
  16. )
  17. type ServiceContext struct {
  18. Config {{.config}}
  19. {{.middleware}}
  20. }
  21. func NewServiceContext(c {{.config}}) *ServiceContext {
  22. return &ServiceContext{
  23. Config: c,
  24. {{.middlewareAssignment}}
  25. }
  26. }
  27. `
  28. )
  29. func genServiceContext(dir string, cfg *config.Config, api *spec.ApiSpec) error {
  30. filename, err := format.FileNamingFormat(cfg.NamingFormat, contextFilename)
  31. if err != nil {
  32. return err
  33. }
  34. var authNames = getAuths(api)
  35. var auths []string
  36. for _, item := range authNames {
  37. auths = append(auths, fmt.Sprintf("%s config.AuthConfig", item))
  38. }
  39. parentPkg, err := getParentPackage(dir)
  40. if err != nil {
  41. return err
  42. }
  43. var middlewareStr string
  44. var middlewareAssignment string
  45. var middlewares = getMiddleware(api)
  46. for _, item := range middlewares {
  47. middlewareStr += fmt.Sprintf("%s rest.Middleware\n", item)
  48. name := strings.TrimSuffix(item, "Middleware") + "Middleware"
  49. middlewareAssignment += fmt.Sprintf("%s: %s,\n", item,
  50. fmt.Sprintf("middleware.New%s().%s", strings.Title(name), "Handle"))
  51. }
  52. var configImport = "\"" + ctlutil.JoinPackages(parentPkg, configDir) + "\""
  53. if len(middlewareStr) > 0 {
  54. configImport += "\n\t\"" + ctlutil.JoinPackages(parentPkg, middlewareDir) + "\""
  55. configImport += fmt.Sprintf("\n\t\"%s/rest\"", vars.ProjectOpenSourceURL)
  56. }
  57. return genFile(fileGenConfig{
  58. dir: dir,
  59. subdir: contextDir,
  60. filename: filename + ".go",
  61. templateName: "contextTemplate",
  62. category: category,
  63. templateFile: contextTemplateFile,
  64. builtinTemplate: contextTemplate,
  65. data: map[string]string{
  66. "configImport": configImport,
  67. "config": "config.Config",
  68. "middleware": middlewareStr,
  69. "middlewareAssignment": middlewareAssignment,
  70. },
  71. })
  72. }