genconfig.go 1.2 KB

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