response.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package response
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. type Response struct {
  7. Code int `json:"code"`
  8. Data interface{} `json:"data"`
  9. Msg string `json:"msg"`
  10. }
  11. const (
  12. ERROR = 201
  13. SUCCESS = 200
  14. )
  15. func Result(code int, data interface{}, msg string, c *gin.Context) {
  16. // 开始时间
  17. c.JSON(http.StatusOK, Response{
  18. code,
  19. data,
  20. msg,
  21. })
  22. }
  23. func Ok(c *gin.Context) {
  24. Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
  25. }
  26. func ReturnErr(err error, c *gin.Context) {
  27. if err != nil {
  28. FailWithError(err, c)
  29. } else {
  30. OkWithMessage("操作成功", c)
  31. }
  32. }
  33. func ReturnErrData(err error, data interface{}, c *gin.Context) {
  34. if err != nil {
  35. FailWithError(err, c)
  36. } else {
  37. OkWithData(data, c)
  38. }
  39. }
  40. func OkWithMessage(message string, c *gin.Context) {
  41. Result(SUCCESS, map[string]interface{}{}, message, c)
  42. }
  43. func OkWithData(data interface{}, c *gin.Context) {
  44. Result(SUCCESS, data, "操作成功", c)
  45. }
  46. func OkWithDetailed(data interface{}, message string, c *gin.Context) {
  47. Result(SUCCESS, data, message, c)
  48. }
  49. func Fail(c *gin.Context) {
  50. Result(ERROR, map[string]interface{}{}, "操作失败", c)
  51. }
  52. func FailWithError(err error, c *gin.Context) {
  53. Result(ERROR, map[string]interface{}{}, err.Error(), c)
  54. }
  55. func FailWithMessage(message string, c *gin.Context) {
  56. Result(ERROR, map[string]interface{}{}, message, c)
  57. }
  58. func FailWithDetailed(data interface{}, message string, c *gin.Context) {
  59. Result(ERROR, data, message, c)
  60. }