gin/define/context.go

69 lines
1.7 KiB
Go

// Package define ...
//
// Description : define ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-04-12 20:57
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"
)
type Context struct {
Context *gin.Context // 继承 gin context
Trace *trace.Runtime // trace 实例
TraceID string
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{
Context: 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
}