feat 添加Response构造函数

This commit is contained in:
timerzz 2024-08-26 16:14:24 +08:00
parent 651c11c544
commit 383f4844cf

View File

@ -1,6 +1,9 @@
package web
import (
"net/http"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/pkg/errors"
)
@ -10,16 +13,44 @@ type ListResponse[E any] struct {
List []E `json:"list"`
}
func (l *ListResponse[E]) SetTotal(total int64) *ListResponse[E] {
l.Total = total
return l
}
func (l *ListResponse[E]) SetList(list []E) *ListResponse[E] {
l.List = list
return l
}
func NewListResponse[E any](total int64, list []E) *ListResponse[E] {
return &ListResponse[E]{
Total: total,
List: list,
}
}
type Response struct {
Code int `json:"code"`
Msg string `json:"msg,omitempty"`
Data interface{} `json:"data,omitempty"`
}
func (r *Response) SetCode(code int) *Response {
r.Code = code
return r
}
func NewResponse(data interface{}, msg ...string) *Response {
return &Response{
Code: http.StatusOK,
Msg: strings.Join(msg, ","),
Data: data,
}
}
func ErrHandle(ctx fiber.Ctx, err error) error {
// Status code defaults to 500
code := fiber.StatusInternalServerError
// Retrieve the custom status code if it's a *fiber.Error
var e *fiber.Error
if errors.As(err, &e) {