From ce2190e3dedaa26a79d42daa2d15c46911ebb226 Mon Sep 17 00:00:00 2001 From: Yun Date: Sun, 7 Dec 2025 11:21:00 +0800 Subject: [PATCH] =?UTF-8?q?=E5=93=8D=E5=BA=94=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- response.go | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/response.go b/response.go index f557b55..ea27e27 100644 --- a/response.go +++ b/response.go @@ -14,6 +14,14 @@ import ( "github.com/zeromicro/go-zero/core/trace" ) +type response struct { + Code int `json:"code"` + Message string `json:"message"` + Data any `json:"data,omitempty"` + Pagination *pagination `json:"pagination,omitempty"` + TraceId string `json:"trace_id,omitempty"` +} + type pagination struct { Page int64 `json:"page"` Size int64 `json:"size"` @@ -101,34 +109,32 @@ func ResponseCtx(ctx context.Context, w http.ResponseWriter, ops ...Option) { o(def) } - res := make(map[string]interface{}) - res["code"] = def.code - res["message"] = def.message - - if def.data != nil { - res["data"] = def.data - } - if def.pagination != nil { - res["pagination"] = def.pagination - } + resp := response{} + resp.Code = def.code + resp.Message = def.message + resp.Data = def.data + resp.Pagination = def.pagination // 获取trace_id if def.traceId != "" { t := ctx.Value(def.traceId) if t != nil { - res["trace_id"] = t + val, ok := t.(string) + if ok { + resp.TraceId = val + } } else { // go-zero - res["trace_id"] = trace.TraceIDFromContext(ctx) + resp.TraceId = trace.TraceIDFromContext(ctx) } } if !def.ignoreLog { // 记录日志 - def.logger.Info(ctx, res) + def.logger.Info(ctx, "response:", resp) } - bs, _ := json.Marshal(res) + bs, _ := json.Marshal(resp) w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(200)