base.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package response
  2. import (
  3. "github.com/gin-gonic/gin"
  4. )
  5. var (
  6. OK_CODE = 200
  7. FAIL_CODE = 400
  8. TOKEN_ERROR_CODE = 401
  9. )
  10. type ResultData struct {
  11. Code int `json:"code" description:"状态码"`
  12. Msg string `json:"msg" description:"提示信息"`
  13. Data interface{} `json:"data" description:"返回数据"`
  14. }
  15. func result(code int, resultData ResultData, c *gin.Context) {
  16. //jsonByte, _ := json.Marshal(resultData)
  17. //global.LOG.Debug("resultData:", string(jsonByte))
  18. c.JSON(code, resultData)
  19. }
  20. // OK 操作成功
  21. func Ok(msg string, c *gin.Context) {
  22. resultData := ResultData{
  23. Code: OK_CODE,
  24. Msg: msg,
  25. }
  26. result(200, resultData, c)
  27. }
  28. // OkData 成功返回数据
  29. func OkData(msg string, data interface{}, c *gin.Context) {
  30. resultData := ResultData{
  31. Code: OK_CODE,
  32. Msg: msg,
  33. Data: data,
  34. }
  35. result(200, resultData, c)
  36. }
  37. // Fail 操作失败
  38. func Fail(msg string, c *gin.Context) {
  39. resultData := ResultData{
  40. Code: FAIL_CODE,
  41. Msg: msg,
  42. }
  43. result(200, resultData, c)
  44. }
  45. // FailData 成功返回数据
  46. func FailData(msg string, data interface{}, c *gin.Context) {
  47. resultData := ResultData{
  48. Code: FAIL_CODE,
  49. Msg: msg,
  50. Data: data,
  51. }
  52. result(200, resultData, c)
  53. }
  54. // Custom 自定义状态码+操作成功
  55. func Custom(code int, msg string, c *gin.Context) {
  56. resultData := ResultData{
  57. Code: code,
  58. Msg: msg,
  59. }
  60. result(200, resultData, c)
  61. }
  62. // CustomData 自定义状态码+返回数据
  63. func CustomData(code int, msg string, data interface{}, c *gin.Context) {
  64. resultData := ResultData{
  65. Code: code,
  66. Msg: msg,
  67. Data: data,
  68. }
  69. result(200, resultData, c)
  70. }
  71. //token异常
  72. func TokenError(data interface{}, message string, c *gin.Context) {
  73. resultData := ResultData{
  74. Code: TOKEN_ERROR_CODE,
  75. Msg: message,
  76. Data: data,
  77. }
  78. result(200, resultData, c)
  79. }