132 lines
2.8 KiB
Go
Raw Permalink Normal View History

2024-10-18 17:19:19 +08:00
package response
import (
"github.com/gin-gonic/gin"
"net/http"
"website-nav/component"
"website-nav/utils"
)
type PageData[T any] struct {
Current int `json:"current"` // 当前页码
Size int `json:"size"` // 每页数量
Total int64 `json:"total"` // 总数
TotalPage int `json:"totalPage"` // 总页数
Records T `json:"records"` // 返回数据
}
type HttpResponse struct{ *gin.Context }
func R(c *gin.Context) HttpResponse {
return HttpResponse{c}
}
// OK
// @description: success
// @receiver h
func (h HttpResponse) OK() {
h.Context.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"message": "success",
})
}
// OkWithData
// @description: success with data
// @receiver h
// @param data
func (h HttpResponse) OkWithData(data any) {
h.Context.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"message": "success",
"data": data,
})
}
// Paginate
// @description: success page data
// @receiver h
// @param data
// @param total
// @param current
// @param size
func (h HttpResponse) Paginate(data any, total int64, current, size int64) {
// 处理一下页码、页数量
if current == -1 {
current = 1
size = total
}
// 计算总页码
totalPage := utils.Paginate().Generate(total, int(size))
// 返回结果
h.Context.JSON(http.StatusOK, map[string]any{
"code": http.StatusOK,
"data": &PageData[any]{Current: int(current), Size: int(size), Total: total, TotalPage: totalPage, Records: data},
"message": "success",
})
}
// AuthorizationFailed
// @description: authorization failed
// @receiver h
// @param msg
func (h HttpResponse) AuthorizationFailed(msg string) {
if msg == "" {
msg = "authorized failed"
}
h.Context.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": msg,
})
}
// Failed
// @description: request bad
// @receiver h
func (h HttpResponse) Failed() {
h.Context.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "failed",
})
}
// FailedWithError
// @description: custom error
// @receiver h
// @param err
func (h HttpResponse) FailedWithError(err any) {
var errStr string
switch err.(type) {
case error:
errStr = err.(error).Error()
case string:
errStr = err.(string)
}
h.Context.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": errStr,
})
}
// Validator
// @description: request param error
// @receiver h
// @param err
func (h HttpResponse) Validator(err error) {
h.Context.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": component.Validate().Error(err),
})
}
// Internal
// @description: server error
// @receiver h
func (h HttpResponse) Internal() {
h.Context.JSON(http.StatusInternalServerError, gin.H{
"code": http.StatusInternalServerError,
"message": "server error",
})
}