gensvc.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package gogen
  2. import (
  3. "fmt"
  4. "strings"
  5. "git.i2edu.net/i2/go-zero/tools/goctl/api/spec"
  6. "git.i2edu.net/i2/go-zero/tools/goctl/config"
  7. ctlutil "git.i2edu.net/i2/go-zero/tools/goctl/util"
  8. "git.i2edu.net/i2/go-zero/tools/goctl/util/format"
  9. "git.i2edu.net/i2/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, rootPkg 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. authNames := getAuths(api)
  35. var auths []string
  36. for _, item := range authNames {
  37. auths = append(auths, fmt.Sprintf("%s config.AuthConfig", item))
  38. }
  39. var middlewareStr string
  40. var middlewareAssignment string
  41. middlewares := getMiddleware(api)
  42. for _, item := range middlewares {
  43. middlewareStr += fmt.Sprintf("%s rest.Middleware\n", item)
  44. name := strings.TrimSuffix(item, "Middleware") + "Middleware"
  45. middlewareAssignment += fmt.Sprintf("%s: %s,\n", item,
  46. fmt.Sprintf("middleware.New%s().%s", strings.Title(name), "Handle"))
  47. }
  48. configImport := "\"" + ctlutil.JoinPackages(rootPkg, configDir) + "\""
  49. if len(middlewareStr) > 0 {
  50. configImport += "\n\t\"" + ctlutil.JoinPackages(rootPkg, middlewareDir) + "\""
  51. configImport += fmt.Sprintf("\n\t\"%s/rest\"", vars.ProjectOpenSourceURL)
  52. }
  53. return genFile(fileGenConfig{
  54. dir: dir,
  55. subdir: contextDir,
  56. filename: filename + ".go",
  57. templateName: "contextTemplate",
  58. category: category,
  59. templateFile: contextTemplateFile,
  60. builtinTemplate: contextTemplate,
  61. data: map[string]string{
  62. "configImport": configImport,
  63. "config": "config.Config",
  64. "middleware": middlewareStr,
  65. "middlewareAssignment": middlewareAssignment,
  66. },
  67. })
  68. }