recommender/internal/handler/http/response/response.go

135 lines
2.3 KiB
Go
Raw Normal View History

2024-11-07 10:09:13 +00:00
package response
2024-11-06 10:47:56 +00:00
import (
"github.com/gin-gonic/gin"
2024-11-07 10:09:13 +00:00
"leafdev.top/Ecosystem/recommender/internal/schema"
2024-11-06 10:47:56 +00:00
"net/http"
)
type HttpResponse struct {
2024-11-07 10:09:13 +00:00
body *schema.ResponseBody
2024-11-06 10:47:56 +00:00
httpStatus int
ctx *gin.Context
}
2024-11-07 10:09:13 +00:00
func NewResponse() *HttpResponse {
2024-11-06 10:47:56 +00:00
return &HttpResponse{
2024-11-07 10:09:13 +00:00
body: &schema.ResponseBody{
2024-11-06 10:47:56 +00:00
Wrap: true,
},
httpStatus: 0,
}
}
func (r *HttpResponse) Message(message string) *HttpResponse {
r.body.Message = message
if r.httpStatus == 0 {
r.httpStatus = http.StatusOK
}
return r
}
// WithoutWrap 将不在 body 中包裹 data
func (r *HttpResponse) WithoutWrap() *HttpResponse {
r.body.Wrap = false
return r
}
func (r *HttpResponse) Wrap() *HttpResponse {
r.body.Wrap = true
return r
}
func (r *HttpResponse) Data(data any) *HttpResponse {
r.body.Data = data
return r
}
func (r *HttpResponse) Error(err error) *HttpResponse {
if err != nil {
var errMsg = err.Error()
if errMsg == "EOF" {
errMsg = "Request body is empty or missing some fields, make sure you have provided all the required fields"
}
r.body.Error = errMsg
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 *HttpResponse) Status(status int) *HttpResponse {
r.httpStatus = status
return r
}
func (r *HttpResponse) Send() {
2024-11-07 10:09:13 +00:00
2024-11-06 10:47:56 +00:00
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 r.body.Wrap {
r.ctx.JSON(r.httpStatus, r.body)
return
}
r.ctx.JSON(r.httpStatus, r.body.Data)
}
func (r *HttpResponse) Abort() {
r.ctx.Abort()
}
//
//func ResponseMessage(c *gin.Context, code int, message string, data interface{}) {
// c.JSON(code, &ResponseBody{
// Message: message,
// Data: data,
// })
// c.Abort()
//}
//
//func ResponseError(c *gin.Context, code int, err error) {
// c.JSON(code, &ResponseBody{
// Error: err.Error(),
// })
// c.Abort()
//}
//
//func Response(c *gin.Context, code int, data interface{}) {
// c.JSON(code, &ResponseBody{
// Data: data,
// })
// c.Abort()
//}
2024-11-07 10:09:13 +00:00
func Ctx(c *gin.Context) *HttpResponse {
return &HttpResponse{
body: &schema.ResponseBody{
Wrap: true,
},
ctx: c,
httpStatus: 0,
}
}