gtoken_resp.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package gtoken
  2. import (
  3. "encoding/json"
  4. "github.com/gogf/gf/util/gconv"
  5. )
  6. const (
  7. SUCCESS = 0
  8. FAIL = -1
  9. ERROR = -99
  10. UNAUTHORIZED = -401
  11. //配置
  12. TypeConfig = 1
  13. // 字典
  14. TypeDict = 2
  15. )
  16. type Resp struct {
  17. Code int `json:"code"`
  18. Msg string `json:"msg"`
  19. Data interface{} `json:"data"`
  20. }
  21. // 获取Data值转字符串
  22. func (resp Resp) Success() bool {
  23. return resp.Code == SUCCESS
  24. }
  25. // 获取Data转字符串
  26. func (resp Resp) DataString() string {
  27. return gconv.String(resp.Data)
  28. }
  29. // 获取Data转Int
  30. func (resp Resp) DataInt() int {
  31. return gconv.Int(resp.Data)
  32. }
  33. // 获取Data值转字符串
  34. func (resp Resp) GetString(key string) string {
  35. return gconv.String(resp.Get(key))
  36. }
  37. // 获取Data值转Int
  38. func (resp Resp) GetInt(key string) int {
  39. return gconv.Int(resp.Get(key))
  40. }
  41. // 获取Data值
  42. func (resp Resp) Get(key string) interface{} {
  43. m := gconv.Map(resp.Data)
  44. if m == nil {
  45. return ""
  46. }
  47. return m[key]
  48. }
  49. func (resp Resp) Json() string {
  50. str, _ := json.Marshal(resp)
  51. return string(str)
  52. }
  53. // 成功
  54. func Succ(data interface{}) Resp {
  55. return Resp{SUCCESS, "success", data}
  56. }
  57. func SuccWithMsg(msg string, data interface{}) Resp {
  58. return Resp{SUCCESS, msg, data}
  59. }
  60. // 失败
  61. func Fail(msg string) Resp {
  62. return Resp{FAIL, msg, ""}
  63. }
  64. // 失败设置Data
  65. func FailData(msg string, data interface{}) Resp {
  66. return Resp{FAIL, msg, data}
  67. }
  68. // 错误
  69. func Error(msg string) Resp {
  70. return Resp{ERROR, msg, ""}
  71. }
  72. // 错误设置Data
  73. func ErrorData(msg string, data interface{}) Resp {
  74. return Resp{ERROR, msg, data}
  75. }
  76. // 认证失败
  77. func Unauthorized(msg string, data interface{}) Resp {
  78. return Resp{UNAUTHORIZED, msg, data}
  79. }