response.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package controller
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "icloudapp.cn/tools/entity"
  5. "net/http"
  6. )
  7. /*
  8. {
  9. "code": 10000, // 程序中的错误码
  10. "msg": xx, // 提示信息
  11. "data": {}, // 数据
  12. }
  13. */
  14. type ResponseData struct {
  15. Code entity.ResCode `json:"code"`
  16. Msg interface{} `json:"msg"`
  17. Body interface{} `json:"data,omitempty"`
  18. }
  19. type ResponseBodyData struct {
  20. Code entity.ResCode `json:"code"`
  21. Msg interface{} `json:"msg"`
  22. Body interface{} `json:"body:omitempty"`
  23. }
  24. // Response error
  25. func ResponseError(c *gin.Context, code entity.ResCode) {
  26. c.JSON(http.StatusOK, &ResponseData{
  27. Code: code,
  28. Msg: code.Msg(),
  29. Body: nil,
  30. })
  31. }
  32. // Response error with msg
  33. func ResponseErrorWithMsg(c *gin.Context, code entity.ResCode, msg interface{}) {
  34. c.JSON(http.StatusOK, &ResponseData{
  35. Code: code,
  36. Msg: msg,
  37. Body: nil,
  38. })
  39. }
  40. // Response success
  41. func ResponseSuccess(c *gin.Context, data interface{}) {
  42. c.JSON(http.StatusOK, &ResponseData{
  43. Code: entity.CodeSuccess,
  44. Msg: entity.CodeSuccess.Msg(),
  45. Body: data,
  46. })
  47. }
  48. // Response {code, msg, body}
  49. func ResponseNormal(c *gin.Context, code entity.ResCode, msg interface{}, body interface{}) {
  50. c.JSON(http.StatusOK, &ResponseData{
  51. Code: code,
  52. Msg: msg,
  53. Body: body,
  54. })
  55. }
  56. func ResponseBody(c *gin.Context, code entity.ResCode, msg interface{}, body interface{}) {
  57. c.JSON(http.StatusOK, &ResponseBodyData{
  58. Code: code,
  59. Msg: msg,
  60. Body: body,
  61. })
  62. }