响应优化

This commit is contained in:
Yun
2025-12-07 11:21:00 +08:00
parent cd0df49d4b
commit ce2190e3de
+20 -14
View File
@@ -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)