package responsex // Author: Yun // Version: 2023年6月12日19:25:54 import ( "context" "encoding/json" "math" "net/http" "github.com/yuninks/langx" "github.com/yuninks/errorx" "github.com/zeromicro/go-zero/core/trace" ) type pagination struct { Page int64 `json:"page"` Size int64 `json:"size"` TotalPage int64 `json:"total_page"` TotalCount int64 `json:"total_count"` } // 计算DB分页偏移量 func GetOffset(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 GetPage(page, size, totalCount int64) pagination { pa := pagination{} totalPage := 0 if size != 0 { totalPage = int(math.Ceil(float64(totalCount) / float64(size))) } pa.Page = page pa.Size = size pa.TotalPage = int64(totalPage) pa.TotalCount = totalCount return pa } // Msg格式化响应 func FormatMessage(ctx context.Context, w http.ResponseWriter, message string, format map[string]string, data interface{}) { code, msg := langx.GetTransFormatCtx(ctx, message, format) ResponseCtx(ctx, w, code, msg, data) } // 成功的响应 func Success(ctx context.Context, w http.ResponseWriter, data interface{}, info ...interface{}) { ResponseCtx(ctx, w, op.defaultSuccessCode, "请求成功", data, info) } func SuccessWithPage(ctx context.Context, w http.ResponseWriter, data interface{}, page pagination) { ResponseCtx(ctx, w, op.defaultSuccessCode, "请求成功", data, page) } // 失败的响应 func Error(ctx context.Context, w http.ResponseWriter, err error) { code := op.defaultErrorCode msg := "请求失败" if err != nil { val, ok := err.(errorx.ErrorInterface) if ok { if langx.GetDefaultCode() != val.GetCode() { code = val.GetCode() } } msg = err.Error() } ResponseCtx(ctx, w, code, msg, "") } func ErrorStr(ctx context.Context, w http.ResponseWriter, msg string) { msg = langx.GetMsgCtx(ctx, msg) code := langx.GetCode(msg) if code == langx.GetDefaultCode() { code = op.defaultErrorCode } ResponseCtx(ctx, w, code, msg, "") } // 基础的响应 func ResponseCtx(ctx context.Context, w http.ResponseWriter, code int, message string, data interface{}, other ...interface{}) { res := make(map[string]interface{}) res["code"] = code res["message"] = message // 分页的内容 var page *pagination for _, value := range other { vv, ok := value.(pagination) if ok { page = &vv } } if page == nil { // 不需要分页 res["data"] = data } else { res["data"] = data res["pagination"] = page } // 获取trace_id if op.traceId != "" { t := ctx.Value(op.traceId) if t != nil { res["trace_id"] = t } else { // go-zero res["trace_id"] = trace.TraceIDFromContext(ctx) } } if !op.ignoreLog { // 记录日志 op.logger.Info(ctx, res) } bs, _ := json.Marshal(res) w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(200) n, err := w.Write(bs) if err != nil || n != len(bs) { op.logger.Error(ctx, "write response failed err:%+v", err) } }