package response import ( "net/http" "strings" "surveyService/util/validator" "github.com/gin-gonic/gin" ) type JSONResult[T any] struct { Code int `json:"code"` Msg string `json:"message"` Data T `json:"data"` } type ListResponse[T any] struct { List []*T `json:"list"` } type PaginateResponse[T any] struct { List []*T `json:"list"` Total int `json:"total"` } type OffsetResponse[T any] struct { List []*T `json:"list"` Offset any `json:"offset"` } type OffsetTotalResponse[T any] struct { List []*T `json:"list"` Total int64 `json:"total"` Offset any `json:"offset"` } // 成功响应 func Success[T any](ctx *gin.Context, data T) { ctx.JSON(http.StatusOK, &JSONResult[T]{ Code: ErrSuccess.Code, Msg: ErrSuccess.Msg, Data: data, }) } // 其他响应 func Response[T any](ctx *gin.Context, data T) { ctx.JSON(http.StatusOK, &data) } // 错误响应 func Fail(c *gin.Context, errcode *ErrCode, msg ...string) { var errMsg string if len(msg) > 0 { errMsg = strings.Join(msg, "") } else { //错误提示优化, 增加错误展示方式 errMsg = errcode.Msg } var T any = struct{}{} c.JSON(http.StatusOK, &JSONResult[any]{ Code: errcode.Code, Msg: errMsg, Data: T, }) c.Abort() } // 错误响应 func FailValidator(c *gin.Context, err error) { var T any = struct{}{} validatorError := validator.TranslateError(err) c.JSON(http.StatusOK, &JSONResult[any]{ Code: VALIDATOR_ERROR, Msg: validatorError.Error(), Data: T, }) c.Abort() }