leaf-library-3/internal/pkg/response/response.go
2024-12-10 18:22:14 +08:00

171 lines
2.9 KiB
Go

package response
import (
"net/http"
"github.com/gofiber/fiber/v2"
)
type IError interface {
Error() string
}
type ValidateError struct {
Message string `json:"message"`
}
// Body 为 HTTP 响应
type Body struct {
Message string `json:"message"`
Error string `json:"error"`
Success bool `json:"success"`
Data any `json:"data,omitempty"`
Wrap bool `json:"-"`
}
type Response struct {
body *Body
httpStatus int
ctx *fiber.Ctx
}
func Ctx(c *fiber.Ctx) *Response {
return &Response{
body: &Body{
Wrap: false,
},
ctx: c,
httpStatus: 0,
}
}
func (r *Response) Message(message string) *Response {
r.body.Message = message
if r.httpStatus == 0 {
r.httpStatus = http.StatusOK
}
return r
}
// Wrap 将在响应中包裹 data
func (r *Response) Wrap() *Response {
r.body.Wrap = true
return r
}
func (r *Response) Data(data any) *Response {
r.body.Data = data
return r
}
func (r *Response) Error(err IError) *Response {
if err != nil {
r.body.Error = err.Error()
if r.httpStatus == 0 {
r.httpStatus = http.StatusBadRequest
}
if r.body.Message == "" {
r.Message("Something went wrong")
}
r.body.Success = false
}
return r
}
func (r *Response) Status(status int) *Response {
r.httpStatus = status
return r
}
func (r *Response) Send() error {
if r.httpStatus == 0 {
r.httpStatus = http.StatusOK
}
// if 20x or 20x, set success
r.body.Success = r.httpStatus >= http.StatusOK && r.httpStatus < http.StatusMultipleChoices
// if 403 or 401 but not have message
if r.httpStatus == http.StatusForbidden || r.httpStatus == http.StatusUnauthorized {
if r.body.Message == "" {
r.Message("Unauthorized")
}
}
// if 400 bad request but not have message
if r.httpStatus == http.StatusBadRequest {
if r.body.Message == "" {
r.Message("Bad request")
}
}
var rspCtx = r.ctx.Status(r.httpStatus)
var rspErr error
if r.body.Data == nil {
return rspCtx.Send([]byte{})
}
if r.body.Wrap {
rspErr = rspCtx.JSON(r.body)
}
rspErr = rspCtx.JSON(r.body.Data)
return rspErr
}
func (r *Response) Success(data any) *Response {
r.body.Data = data
r.body.Success = true
if r.httpStatus == 0 {
r.httpStatus = http.StatusOK
}
return r
}
//func (r *Response) ValidationError(validationErrors *[]ValidateError) *Response {
// if validationErrors == nil || len(*validationErrors) == 0 {
// }
//
// r.body.ValidationErrors = validationErrors
//
// r.Error(errs.ErrBadRequest)
//
// return r
//}
//
//func ResponseMessage(c *gin.Context, code int, message string, data interface{}) {
// c.JSON(code, &Body{
// Message: message,
// Data: data,
// })
// c.Abort()
//}
//
//func ResponseError(c *gin.Context, code int, err error) {
// c.JSON(code, &Body{
// Error: err.Error(),
// })
// c.Abort()
//}
//
//func Response(c *gin.Context, code int, data interface{}) {
// c.JSON(code, &Body{
// Data: data,
// })
// c.Abort()
//}