response.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. ERROR_TIMEOUT = 11 // 总线信息超时
  16. SUCCESS = 0
  17. )
  18. func Result(code int, data interface{}, msg string, c *gin.Context) {
  19. // 开始时间
  20. c.JSON(http.StatusOK, Response{
  21. code,
  22. data,
  23. msg,
  24. })
  25. }
  26. func Ok(c *gin.Context) {
  27. Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
  28. }
  29. func OkWithMessage(message string, c *gin.Context) {
  30. Result(SUCCESS, map[string]interface{}{}, message, c)
  31. }
  32. func OkWithData(data interface{}, c *gin.Context) {
  33. Result(SUCCESS, data, "操作成功", c)
  34. }
  35. func OkWithDetailed(data interface{}, message string, c *gin.Context) {
  36. Result(SUCCESS, data, message, c)
  37. }
  38. func Fail(c *gin.Context) {
  39. Result(ERROR, map[string]interface{}{}, "操作失败", c)
  40. }
  41. func FailWithMessage(message string, c *gin.Context) {
  42. Result(ERROR, map[string]interface{}{}, message, c)
  43. }
  44. func FailWithDetailed(data interface{}, message string, c *gin.Context) {
  45. Result(ERROR, data, message, c)
  46. }
  47. func FailWithCodeAndDetail(data interface{}, code int, message string, c *gin.Context) {
  48. Result(code, data, message, c)
  49. }