Resopnse.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package resopnse
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. // 这里定义的状态码
  7. type Rescode int64
  8. // 在const里使用了iota自增
  9. const (
  10. CodeSuccess Rescode = 1000 + iota
  11. CodeInvalidParam
  12. CodeUserExist
  13. CodeUserNotExist
  14. CodeNotMatch
  15. CodeServerBusy
  16. )
  17. // 给对应状态码加上消息
  18. var codeMsgMap = map[Rescode]string{
  19. CodeSuccess: "success",
  20. CodeInvalidParam: "请求参数错误",
  21. CodeUserExist: "用户名已存在",
  22. CodeUserNotExist: "用户不存在",
  23. CodeNotMatch: "用户名或密码错误",
  24. CodeServerBusy: "服务器繁忙",
  25. // 比如数据库连接错误啥的,前端不用知道,
  26. // 就说服务器繁忙就行
  27. }
  28. // 获得对应状态码的消息
  29. func (c Rescode) GetMsg() string {
  30. msg, ok := codeMsgMap[c]
  31. if !ok {
  32. msg = codeMsgMap[CodeServerBusy]
  33. }
  34. return msg
  35. }
  36. /*
  37. 封装响应方法,固定格式,方便前端
  38. {
  39. "code": , //程序中的错误码
  40. "msg": ,// 错误的提示信息
  41. "data":{} //数据
  42. }
  43. */
  44. type ResopnseDate struct {
  45. Code Rescode `json:"code"`
  46. Msg interface{} `json:"msg"`
  47. Date interface{} `json:"data"`
  48. }
  49. func ResponseError(c *gin.Context, code Rescode) {
  50. //只有状态码
  51. c.JSON(http.StatusOK, &ResopnseDate{
  52. Code: code,
  53. Msg: code.GetMsg(),
  54. Date: nil,
  55. })
  56. }
  57. func ResponseErrorWithMsg(c *gin.Context, code Rescode, msg interface{}) {
  58. //有状态码和自己的信息
  59. c.JSON(http.StatusOK, &ResopnseDate{
  60. Code: code,
  61. Msg: msg,
  62. Date: nil,
  63. })
  64. }
  65. func ResopnseSuccess(c *gin.Context, data interface{}) {
  66. //成功以后返回的,自带数据
  67. c.JSON(http.StatusOK, &ResopnseDate{
  68. Code: CodeSuccess,
  69. Msg: CodeSuccess.GetMsg(),
  70. Date: data,
  71. })
  72. }