genconfig.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package gogen
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. "text/template"
  7. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  8. "github.com/tal-tech/go-zero/tools/goctl/api/util"
  9. ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  10. "github.com/tal-tech/go-zero/tools/goctl/vars"
  11. )
  12. const (
  13. configFile = "config.go"
  14. configTemplate = `package config
  15. import {{.authImport}}
  16. type Config struct {
  17. rest.RestConf
  18. {{.auth}}
  19. }
  20. `
  21. jwtTemplate = ` struct {
  22. AccessSecret string
  23. AccessExpire int64
  24. }
  25. `
  26. )
  27. func genConfig(dir string, api *spec.ApiSpec) error {
  28. fp, created, err := util.MaybeCreateFile(dir, configDir, configFile)
  29. if err != nil {
  30. return err
  31. }
  32. if !created {
  33. return nil
  34. }
  35. defer fp.Close()
  36. var authNames = getAuths(api)
  37. var auths []string
  38. for _, item := range authNames {
  39. auths = append(auths, fmt.Sprintf("%s %s", item, jwtTemplate))
  40. }
  41. var authImportStr = fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceUrl)
  42. text, err := ctlutil.LoadTemplate(category, configTemplateFile, configTemplate)
  43. if err != nil {
  44. return err
  45. }
  46. t := template.Must(template.New("configTemplate").Parse(text))
  47. buffer := new(bytes.Buffer)
  48. err = t.Execute(buffer, map[string]string{
  49. "authImport": authImportStr,
  50. "auth": strings.Join(auths, "\n"),
  51. })
  52. if err != nil {
  53. return nil
  54. }
  55. formatCode := formatCode(buffer.String())
  56. _, err = fp.WriteString(formatCode)
  57. return err
  58. }