响应优化
This commit is contained in:
+20
-14
@@ -14,6 +14,14 @@ import (
|
|||||||
"github.com/zeromicro/go-zero/core/trace"
|
"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 {
|
type pagination struct {
|
||||||
Page int64 `json:"page"`
|
Page int64 `json:"page"`
|
||||||
Size int64 `json:"size"`
|
Size int64 `json:"size"`
|
||||||
@@ -101,34 +109,32 @@ func ResponseCtx(ctx context.Context, w http.ResponseWriter, ops ...Option) {
|
|||||||
o(def)
|
o(def)
|
||||||
}
|
}
|
||||||
|
|
||||||
res := make(map[string]interface{})
|
resp := response{}
|
||||||
res["code"] = def.code
|
resp.Code = def.code
|
||||||
res["message"] = def.message
|
resp.Message = def.message
|
||||||
|
resp.Data = def.data
|
||||||
if def.data != nil {
|
resp.Pagination = def.pagination
|
||||||
res["data"] = def.data
|
|
||||||
}
|
|
||||||
if def.pagination != nil {
|
|
||||||
res["pagination"] = def.pagination
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取trace_id
|
// 获取trace_id
|
||||||
if def.traceId != "" {
|
if def.traceId != "" {
|
||||||
t := ctx.Value(def.traceId)
|
t := ctx.Value(def.traceId)
|
||||||
if t != nil {
|
if t != nil {
|
||||||
res["trace_id"] = t
|
val, ok := t.(string)
|
||||||
|
if ok {
|
||||||
|
resp.TraceId = val
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// go-zero
|
// go-zero
|
||||||
res["trace_id"] = trace.TraceIDFromContext(ctx)
|
resp.TraceId = trace.TraceIDFromContext(ctx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !def.ignoreLog {
|
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.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
w.WriteHeader(200)
|
w.WriteHeader(200)
|
||||||
|
|||||||
Reference in New Issue
Block a user