封装的方法类
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
package response
|
||||
|
||||
// Author: Yun
|
||||
// Version: 2023年6月12日19:25:54
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"yunink/app/pkg/langx"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type pagination struct {
|
||||
Page int `json:"page"`
|
||||
Size int `json:"size"`
|
||||
TotalPage int `json:"total_page"`
|
||||
TotalCount int `json:"total_count"`
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
func PageToOffset(page, size int) (offset int, limit int) {
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
offset = (page - 1) * size
|
||||
limit = size
|
||||
if limit == 0 {
|
||||
// 默认查10条
|
||||
limit = 10
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 计算分页
|
||||
func GetPagination(page, size, total_count int) pagination {
|
||||
pa := pagination{}
|
||||
total_page := int(math.Ceil(float64(total_count) / float64(size)))
|
||||
pa.Page = page
|
||||
pa.Size = size
|
||||
pa.TotalPage = total_page
|
||||
pa.TotalCount = total_count
|
||||
return pa
|
||||
}
|
||||
|
||||
// Msg格式化响应
|
||||
func FormatMessage(ctx *gin.Context, message langx.MessageKey, mag_param map[string]string, data interface{}) {
|
||||
code, msg := langx.GetTrans(message, mag_param)
|
||||
Response(ctx, code, msg, data)
|
||||
}
|
||||
|
||||
// 成功的响应
|
||||
func Success(ctx *gin.Context, data interface{}, info ...interface{}) {
|
||||
Response(ctx, 200, "请求成功", data, info)
|
||||
}
|
||||
|
||||
func SuccessWithPage(ctx *gin.Context, data interface{}, page pagination) {
|
||||
Response(ctx, 200, "请求成功", data, page)
|
||||
}
|
||||
|
||||
// 失败的响应
|
||||
func Error(ctx *gin.Context, msg string) {
|
||||
Response(ctx, 400, msg, "")
|
||||
}
|
||||
|
||||
// 基础的响应
|
||||
func Response(ctx *gin.Context, code int, message string, data interface{}, other ...interface{}) {
|
||||
|
||||
res := make(map[string]interface{})
|
||||
|
||||
res["code"] = code
|
||||
res["message"] = message
|
||||
|
||||
// data没有值则为空
|
||||
if data != "" {
|
||||
res["data"] = data
|
||||
}
|
||||
|
||||
// 分页的内容
|
||||
for _, value := range other {
|
||||
pagination, ok := value.(pagination)
|
||||
if ok {
|
||||
res["pagination"] = pagination
|
||||
}
|
||||
}
|
||||
|
||||
// log.Print(res)
|
||||
|
||||
ctx.JSON(http.StatusOK, res)
|
||||
}
|
||||
Reference in New Issue
Block a user