response.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 = 7
  13. ERROR_TOKEN_EXPIRED = 8 // TOKEN过期
  14. ERROR_TOKEN_OTHER_LOGIN = 9 // 异地登录
  15. SUCCESS = 0
  16. )
  17. func Result(code int, data interface{}, msg string, c *gin.Context) {
  18. // 开始时间
  19. c.JSON(http.StatusOK, Response{
  20. code,
  21. data,
  22. msg,
  23. })
  24. }
  25. func Ok(c *gin.Context) {
  26. Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
  27. }
  28. func OkWithMessage(message string, c *gin.Context) {
  29. Result(SUCCESS, map[string]interface{}{}, message, c)
  30. }
  31. func OkWithData(data interface{}, c *gin.Context) {
  32. Result(SUCCESS, data, "操作成功", c)
  33. }
  34. func OkWithDetailed(data interface{}, message string, c *gin.Context) {
  35. Result(SUCCESS, data, message, c)
  36. }
  37. func Fail(c *gin.Context) {
  38. Result(ERROR, map[string]interface{}{}, "操作失败", c)
  39. }
  40. func FailWithMessage(message string, c *gin.Context) {
  41. Result(ERROR, map[string]interface{}{}, message, c)
  42. }
  43. func FailWithDetailed(data interface{}, message string, c *gin.Context) {
  44. Result(ERROR, data, message, c)
  45. }
  46. func FailWithCodeAndDetail(data interface{}, code int, message string, c *gin.Context) {
  47. Result(code, data, message, c)
  48. }