reponse.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package core
  2. import (
  3. "github.com/demdxx/gocast"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. "time"
  7. )
  8. type Response struct {
  9. Code int32 `json:"code"` // 响应码
  10. Msg string `json:"msg"` // 响应消息
  11. Data any `json:"data"` // 响应信息 ,omitempty
  12. Time int64 `json:"time"` // 服务器时间
  13. }
  14. var (
  15. ResponseMissAuthToken = &Response{Code: 501, Msg: "Authorization为空"}
  16. ResponseTokenInvalid = &Response{Code: 501, Msg: "Token过期失效"}
  17. ResponseSignError = &Response{Code: 503, Msg: "签名错误"}
  18. )
  19. func (rc *Response) Error() string {
  20. return rc.Msg
  21. }
  22. func (rc *Response) SetMsg(msg string) *Response {
  23. return &Response{
  24. Code: rc.Code,
  25. Msg: msg,
  26. }
  27. }
  28. func (rc *Response) SetData(data any) *Response {
  29. return &Response{
  30. Code: rc.Code,
  31. Msg: rc.Msg,
  32. Data: data,
  33. }
  34. }
  35. func (rc *Response) setTime() *Response {
  36. return &Response{
  37. Code: rc.Code,
  38. Msg: rc.Msg,
  39. Data: rc.Data,
  40. Time: time.Now().Unix(),
  41. }
  42. }
  43. func newFailErrorMsg(msg string) *Response {
  44. return &Response{Code: 500, Msg: msg, Time: time.Now().Unix()}
  45. }
  46. func newSuccessMsg() *Response {
  47. return &Response{Code: 200, Msg: "success", Time: time.Now().Unix()}
  48. }
  49. func Resp(c *gin.Context, args ...interface{}) {
  50. var data interface{}
  51. if len(args) == 0 {
  52. c.JSON(http.StatusOK, newSuccessMsg())
  53. return
  54. }
  55. data = args[0]
  56. switch data.(type) {
  57. case *Response:
  58. c.JSON(http.StatusOK, data.(*Response).setTime())
  59. case string:
  60. c.JSON(http.StatusOK, newFailErrorMsg(gocast.ToString(data)))
  61. case error:
  62. c.JSON(http.StatusOK, newFailErrorMsg(data.(error).Error()))
  63. default:
  64. c.JSON(http.StatusOK, newSuccessMsg().SetData(data))
  65. }
  66. }