common/pkg/web/response.go

73 lines
1.4 KiB
Go
Raw Normal View History

2024-05-14 20:36:48 +08:00
package web
2024-08-26 16:06:43 +08:00
import (
2024-08-26 16:14:24 +08:00
"net/http"
"strings"
2024-08-26 16:06:43 +08:00
"github.com/gofiber/fiber/v3"
"github.com/pkg/errors"
)
2024-05-14 20:36:48 +08:00
type ListResponse[E any] struct {
Total int64 `json:"total"`
List []E `json:"list"`
}
2024-08-26 16:06:43 +08:00
2024-08-26 16:14:24 +08:00
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,
}
}
2024-08-26 16:06:43 +08:00
type Response struct {
Code int `json:"code"`
Msg string `json:"msg,omitempty"`
Data interface{} `json:"data,omitempty"`
}
2024-08-26 16:14:24 +08:00
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,
}
}
2024-08-26 16:06:43 +08:00
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) {
code = e.Code
}
// Send custom error page
2024-09-10 14:04:55 +08:00
err = ctx.JSON(Response{
2024-08-26 16:06:43 +08:00
Code: code,
Msg: err.Error(),
})
if err != nil {
// In case the SendFile fails
return ctx.Status(fiber.StatusInternalServerError).SendString("Internal Server Error")
}
// Return from handler
return nil
}