response.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package app
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. "zhiyuan/pkg/errcode"
  6. )
  7. type ResponseData struct {
  8. Code int `json:"code"`
  9. Msg string `json:"message"`
  10. Data interface{} `json:"data"`
  11. }
  12. func Response(c *gin.Context, httpCode int, err errcode.Err, data interface{}) {
  13. ResponseBase(c, httpCode, err.Code, err.Msg, data)
  14. }
  15. func ResponseBase(c *gin.Context, httpCode int, code int, msg string, data interface{}) {
  16. if data == nil {
  17. data = make(map[string]interface{})
  18. }
  19. c.JSON(httpCode, ResponseData{
  20. Code: code,
  21. Msg: msg,
  22. Data: data,
  23. })
  24. return
  25. }
  26. func Error(c *gin.Context, msg string) {
  27. ResponseBase(c, http.StatusOK, errcode.InvalidParams.Code, msg, nil)
  28. return
  29. }
  30. func ErrorMsg(c *gin.Context, msg string, data interface{}) {
  31. ResponseBase(c, http.StatusOK, errcode.InvalidParams.Code, msg, data)
  32. return
  33. }
  34. func ErrorCode(c *gin.Context, err errcode.Err, data interface{}) {
  35. Response(c, http.StatusOK, err, data)
  36. return
  37. }
  38. func SuccessMsg(c *gin.Context, msg string, data interface{}) {
  39. ResponseBase(c, http.StatusOK, errcode.Success.Code, msg, data)
  40. return
  41. }
  42. func Success(c *gin.Context, data interface{}) {
  43. Response(c, http.StatusOK, errcode.Success, data)
  44. return
  45. }