response.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package webutils
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. ut "github.com/go-playground/universal-translator"
  6. "github.com/sirupsen/logrus"
  7. )
  8. const (
  9. CodeSuccess = 20000
  10. CodeFailed = -1
  11. CodeIllegalToken = 50008
  12. CodeTokenExpired = 50014
  13. CodeOther = 50012
  14. )
  15. var (
  16. trans ut.Translator
  17. )
  18. type RespError struct {
  19. msg string
  20. }
  21. func NewRespError(msg string) RespError {
  22. return RespError{
  23. msg: msg,
  24. }
  25. }
  26. func (p *RespError) Error() string {
  27. return ""
  28. }
  29. type Response struct {
  30. Code int `json:"code"`
  31. Msg string `json:"msg"`
  32. Data interface{} `json:"data"`
  33. }
  34. type ResponseGen[T interface{}] struct {
  35. Code int `json:"code"`
  36. Msg string `json:"msg"`
  37. Data T `json:"data"`
  38. }
  39. func FailedResponse(c *gin.Context, msg string) {
  40. if c == nil {
  41. return
  42. }
  43. c.JSON(http.StatusOK, &Response{
  44. Code: CodeFailed,
  45. Msg: msg,
  46. Data: nil,
  47. })
  48. panic(kkerror.NewRespError("failed"))
  49. }
  50. func FailedResponseErr(c *gin.Context, err error) {
  51. if c == nil {
  52. return
  53. }
  54. logrus.Error(err)
  55. FailedResponse(c, "内部错误")
  56. }
  57. func FailedResponseWithCode(c *gin.Context, code int, msg string) {
  58. c.JSON(http.StatusOK, &Response{
  59. Code: code,
  60. Msg: msg,
  61. Data: nil,
  62. })
  63. panic(kkerror.NewRespError("failed"))
  64. }
  65. func SuccessResponse(c *gin.Context, data interface{}) {
  66. c.JSON(http.StatusOK, &Response{
  67. Code: CodeSuccess,
  68. Msg: "",
  69. Data: data,
  70. })
  71. panic(kkerror.NewRespError("success"))
  72. }