蛋蛋星球-客户端
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 

113 rader
2.2 KiB

  1. package e
  2. import (
  3. "applet/app/lib/aes"
  4. "applet/app/lib/aes/md"
  5. "applet/app/utils"
  6. "encoding/json"
  7. "net/http"
  8. "github.com/gin-gonic/gin"
  9. "applet/app/utils/logx"
  10. )
  11. // GetMsg get error information based on Code
  12. // 因为这里code是自己控制的, 因此没考虑报错信息
  13. func GetMsg(code int) (int, string) {
  14. if msg, ok := MsgFlags[code]; ok {
  15. return code / 1000, msg
  16. }
  17. if http.StatusText(code) == "" {
  18. code = 200
  19. }
  20. return code, MsgFlags[ERR_BAD_REQUEST]
  21. }
  22. // 成功输出, fields 是额外字段, 与code, msg同级
  23. func OutSuc(c *gin.Context, data interface{}, fields map[string]interface{}) {
  24. res := gin.H{
  25. "code": 1,
  26. "msg": "ok",
  27. "data": data,
  28. }
  29. if fields != nil {
  30. for k, v := range fields {
  31. res[k] = v
  32. }
  33. }
  34. if c.GetBool("is_check_sign") {
  35. jsonData, _ := json.Marshal(res)
  36. str := aes.AesEncryptByECB(md.AesKey, string(jsonData))
  37. c.Writer.WriteString(str)
  38. }
  39. c.AbortWithStatusJSON(200, res)
  40. }
  41. func OutSucPure(c *gin.Context, data interface{}, fields map[string]interface{}) {
  42. res := gin.H{
  43. "code": 1,
  44. "msg": "ok",
  45. "data": data,
  46. }
  47. if fields != nil {
  48. for k, v := range fields {
  49. res[k] = v
  50. }
  51. }
  52. c.Abort()
  53. c.PureJSON(200, res)
  54. }
  55. // 错误输出
  56. func OutErr(c *gin.Context, code int, err ...interface{}) {
  57. statusCode, msg := GetMsg(code)
  58. if len(err) > 0 && err[0] != nil {
  59. e := err[0]
  60. switch v := e.(type) {
  61. case E:
  62. statusCode = v.Code / 1000
  63. msg = v.Error()
  64. logx.Error(v.msg + ": " + v.st) // 记录堆栈信息
  65. case error:
  66. logx.Error(v)
  67. break
  68. case string:
  69. msg = v
  70. case int:
  71. if _, ok := MsgFlags[v]; ok {
  72. msg = MsgFlags[v]
  73. }
  74. }
  75. }
  76. if c.GetBool("is_check_sign") {
  77. jsonData, _ := json.Marshal(gin.H{
  78. "code": code,
  79. "msg": msg,
  80. "data": []struct{}{},
  81. })
  82. str := aes.AesEncryptByECB(md.AesKey, string(jsonData))
  83. if code > 100000 {
  84. code = int(utils.FloatFormat(float64(code/1000), 0))
  85. }
  86. c.Status(500)
  87. c.Writer.WriteString(str)
  88. }
  89. c.AbortWithStatusJSON(statusCode, gin.H{
  90. "code": code,
  91. "msg": msg,
  92. "data": []struct{}{},
  93. })
  94. }
  95. // 重定向
  96. func OutRedirect(c *gin.Context, code int, loc string) {
  97. if code < 301 || code > 308 {
  98. code = 303
  99. }
  100. c.Redirect(code, loc)
  101. c.Abort()
  102. }