response.go 1.3 KB

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