70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
// Package middleware ...
|
|
//
|
|
// Description : middleware ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2022-06-25 23:07
|
|
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.zhangdeman.cn/zhangdeman/wrapper"
|
|
|
|
"git.zhangdeman.cn/zhangdeman/gin/define"
|
|
|
|
networkUtil "git.zhangdeman.cn/zhangdeman/network/util"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// InitRequest 初始化请求
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 23:08 2022/6/25
|
|
func InitRequest() gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
httpHandleConfig := define.GetHttpHandleConfig()
|
|
traceID := getTraceID(ctx)
|
|
requestID := getRequestID(ctx, traceID)
|
|
ctx.Set(httpHandleConfig.TraceIDField, traceID)
|
|
ctx.Set(httpHandleConfig.RequestIDField, requestID)
|
|
ctx.Set(httpHandleConfig.StartRequestTimeField, time.Now().UnixMilli())
|
|
ctx.Next()
|
|
}
|
|
}
|
|
|
|
// getTraceID 生成traceID
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 23:12 2022/6/25
|
|
func getTraceID(ctx *gin.Context) string {
|
|
return fmt.Sprintf(
|
|
"%v-%v-%v-%v",
|
|
time.Now().UnixNano()/1e6,
|
|
strings.ReplaceAll(networkUtil.IP.GetHostIP(), ".", ""),
|
|
strings.ReplaceAll(networkUtil.IP.GetRemoteIP(ctx.Request), ".", ""),
|
|
wrapper.StringFromRandom(32, "").Md5().Value,
|
|
)
|
|
}
|
|
|
|
// getRequestID 生成requestID
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 23:12 2022/6/25
|
|
func getRequestID(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 getTraceID(ctx)
|
|
}
|