广告平台(站长使用)
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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