response.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package response
  2. import (
  3. "net/http"
  4. "strings"
  5. "surveyService/util/validator"
  6. "github.com/gin-gonic/gin"
  7. )
  8. type JSONResult[T any] struct {
  9. Code int `json:"code"`
  10. Msg string `json:"message"`
  11. Data T `json:"data"`
  12. }
  13. type ListResponse[T any] struct {
  14. List []*T `json:"list"`
  15. }
  16. type PaginateResponse[T any] struct {
  17. List []*T `json:"list"`
  18. Total int `json:"total"`
  19. }
  20. type OffsetResponse[T any] struct {
  21. List []*T `json:"list"`
  22. Offset any `json:"offset"`
  23. }
  24. type OffsetTotalResponse[T any] struct {
  25. List []*T `json:"list"`
  26. Total int64 `json:"total"`
  27. Offset any `json:"offset"`
  28. }
  29. // 成功响应
  30. func Success[T any](ctx *gin.Context, data T) {
  31. ctx.JSON(http.StatusOK, &JSONResult[T]{
  32. Code: ErrSuccess.Code,
  33. Msg: ErrSuccess.Msg,
  34. Data: data,
  35. })
  36. }
  37. // 其他响应
  38. func Response[T any](ctx *gin.Context, data T) {
  39. ctx.JSON(http.StatusOK, &data)
  40. }
  41. // 错误响应
  42. func Fail(c *gin.Context, errcode *ErrCode, msg ...string) {
  43. var errMsg string
  44. if len(msg) > 0 {
  45. errMsg = strings.Join(msg, "")
  46. } else {
  47. //错误提示优化, 增加错误展示方式
  48. errMsg = errcode.Msg
  49. }
  50. var T any = struct{}{}
  51. c.JSON(http.StatusOK, &JSONResult[any]{
  52. Code: errcode.Code,
  53. Msg: errMsg,
  54. Data: T,
  55. })
  56. c.Abort()
  57. }
  58. // 错误响应
  59. func FailValidator(c *gin.Context, err error) {
  60. var T any = struct{}{}
  61. validatorError := validator.TranslateError(err)
  62. c.JSON(http.StatusOK, &JSONResult[any]{
  63. Code: VALIDATOR_ERROR,
  64. Msg: validatorError.Error(),
  65. Data: T,
  66. })
  67. c.Abort()
  68. }