gtoken_resp.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. // 失败
  58. func Fail(msg string) Resp {
  59. return Resp{FAIL, msg, ""}
  60. }
  61. // 失败设置Data
  62. func FailData(msg string, data interface{}) Resp {
  63. return Resp{FAIL, msg, data}
  64. }
  65. // 错误
  66. func Error(msg string) Resp {
  67. return Resp{ERROR, msg, ""}
  68. }
  69. // 错误设置Data
  70. func ErrorData(msg string, data interface{}) Resp {
  71. return Resp{ERROR, msg, data}
  72. }
  73. // 认证失败
  74. func Unauthorized(msg string, data interface{}) Resp {
  75. return Resp{UNAUTHORIZED, msg, data}
  76. }