67 lines
1.4 KiB
Go
67 lines
1.4 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/gin/define"
|
|
|
|
"git.zhangdeman.cn/zhangdeman/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) {
|
|
traceID := getTraceID(ctx)
|
|
requestID := getRequestID(ctx, traceID)
|
|
ctx.Set(define.TraceIDField, traceID)
|
|
ctx.Set(define.RequestIDField, requestID)
|
|
ctx.Set(define.StartRequestTimeField, time.Now().UnixNano())
|
|
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(util.IP.GetHostIP(), ".", ""),
|
|
strings.ReplaceAll(util.IP.GetRemoteIP(ctx.Request), ".", ""),
|
|
util.String.Md5(util.String.GenRandom("", 32)),
|
|
)
|
|
}
|
|
|
|
// 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)
|
|
}
|