修复循环引用问题
This commit is contained in:
@ -8,8 +8,13 @@
|
||||
package define
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
networkUtil "git.zhangdeman.cn/zhangdeman/network/util"
|
||||
"git.zhangdeman.cn/zhangdeman/wrapper"
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/trace"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@ -21,3 +26,43 @@ type Context struct {
|
||||
RequestID string
|
||||
RequestTime time.Time
|
||||
}
|
||||
|
||||
// NewContext 创建context
|
||||
func NewContext(ginCtx *gin.Context) *Context {
|
||||
existCtx, exist := ginCtx.Get(CustomContextKey)
|
||||
if exist && existCtx != nil {
|
||||
if c, ok := existCtx.(*Context); ok {
|
||||
return c
|
||||
}
|
||||
}
|
||||
traceID := fmt.Sprintf(
|
||||
"%v-%v-%v-%v",
|
||||
time.Now().UnixNano()/1e6,
|
||||
strings.ReplaceAll(networkUtil.IP.GetHostIP(), ".", ""),
|
||||
strings.ReplaceAll(networkUtil.IP.GetRemoteIP(ginCtx.Request), ".", ""),
|
||||
wrapper.StringFromRandom(32, "").Md5().Value,
|
||||
)
|
||||
getRequestID := func(ctx *gin.Context, traceID string) string {
|
||||
requestID := ctx.GetHeader("X-Forward-Request-Id")
|
||||
if len(requestID) > 0 {
|
||||
return requestID
|
||||
}
|
||||
if len(traceID) > 0 {
|
||||
return traceID
|
||||
}
|
||||
return traceID
|
||||
}
|
||||
ctx := &Context{
|
||||
Gin: ginCtx,
|
||||
Trace: trace.NewRuntime(traceID, 1),
|
||||
TraceID: traceID,
|
||||
RequestID: getRequestID(ginCtx, traceID),
|
||||
RequestTime: time.Now(),
|
||||
}
|
||||
httpHandleConfig := GetHttpHandleConfig()
|
||||
ginCtx.Set(CustomContextKey, ctx)
|
||||
ginCtx.Set(httpHandleConfig.TraceIDField, traceID)
|
||||
ginCtx.Set(httpHandleConfig.RequestIDField, ctx.RequestID)
|
||||
ginCtx.Set(httpHandleConfig.StartRequestTimeField, ctx.RequestTime.UnixMilli())
|
||||
return ctx
|
||||
}
|
||||
|
Reference in New Issue
Block a user