From 383f4844cf3b76a6771871d3a71ee18a9386a3a8 Mon Sep 17 00:00:00 2001 From: timerzz Date: Mon, 26 Aug 2024 16:14:24 +0800 Subject: [PATCH] =?UTF-8?q?feat=20=E6=B7=BB=E5=8A=A0Response=E6=9E=84?= =?UTF-8?q?=E9=80=A0=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/web/response.go | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/pkg/web/response.go b/pkg/web/response.go index a5b163c..84865ef 100644 --- a/pkg/web/response.go +++ b/pkg/web/response.go @@ -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) {