config.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package config
  2. import (
  3. "go/token"
  4. "log"
  5. "github.com/xinliangnote/go-gin-api/configs"
  6. "github.com/xinliangnote/go-gin-api/internal/code"
  7. "github.com/xinliangnote/go-gin-api/internal/pkg/core"
  8. "github.com/xinliangnote/go-gin-api/internal/repository/mysql"
  9. "github.com/xinliangnote/go-gin-api/internal/repository/redis"
  10. "github.com/dave/dst"
  11. "github.com/dave/dst/decorator"
  12. "github.com/spf13/cast"
  13. "go.uber.org/zap"
  14. )
  15. const minBusinessCode = 20000
  16. type handler struct {
  17. logger *zap.Logger
  18. cache redis.Repo
  19. }
  20. func New(logger *zap.Logger, db mysql.Repo, cache redis.Repo) *handler {
  21. return &handler{
  22. logger: logger,
  23. cache: cache,
  24. }
  25. }
  26. func (h *handler) Email() core.HandlerFunc {
  27. return func(ctx core.Context) {
  28. ctx.HTML("config_email", configs.Get())
  29. }
  30. }
  31. func (h *handler) Code() core.HandlerFunc {
  32. type codes struct {
  33. Code int `json:"code"` // 错误码
  34. Message string `json:"message"` // 错误码信息
  35. }
  36. type codeViewResponse struct {
  37. SystemCodes []codes
  38. BusinessCodes []codes
  39. }
  40. parsedFile, err := decorator.Parse(code.ByteCodeFile)
  41. if err != nil {
  42. log.Fatalf("parsing code.go: %s: %s\n", "ByteCodeFile", err)
  43. }
  44. var (
  45. systemCodes []codes
  46. businessCodes []codes
  47. )
  48. dst.Inspect(parsedFile, func(n dst.Node) bool {
  49. // GenDecl 代表除函数以外的所有声明,即 import、const、var 和 type
  50. decl, ok := n.(*dst.GenDecl)
  51. if !ok || decl.Tok != token.CONST {
  52. return true
  53. }
  54. for _, spec := range decl.Specs {
  55. valueSpec, _ok := spec.(*dst.ValueSpec)
  56. if !_ok {
  57. continue
  58. }
  59. codeInt := cast.ToInt(valueSpec.Values[0].(*dst.BasicLit).Value)
  60. if codeInt < minBusinessCode {
  61. systemCodes = append(systemCodes, codes{
  62. Code: codeInt,
  63. Message: code.Text(codeInt),
  64. })
  65. } else {
  66. businessCodes = append(businessCodes, codes{
  67. Code: codeInt,
  68. Message: code.Text(codeInt),
  69. })
  70. }
  71. }
  72. return true
  73. })
  74. return func(ctx core.Context) {
  75. obj := new(codeViewResponse)
  76. obj.BusinessCodes = businessCodes
  77. obj.SystemCodes = systemCodes
  78. ctx.HTML("config_code", obj)
  79. }
  80. }