gin/middleware/init_request.go

70 lines
1.6 KiB
Go
Raw Normal View History

2022-06-25 23:21:02 +08:00
// Package middleware ...
//
// Description : middleware ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-06-25 23:07
package middleware
import (
"fmt"
"strings"
"time"
2023-08-26 13:24:25 +08:00
"git.zhangdeman.cn/zhangdeman/wrapper"
2022-06-25 23:21:02 +08:00
"git.zhangdeman.cn/zhangdeman/gin/define"
2023-08-10 14:47:20 +08:00
networkUtil "git.zhangdeman.cn/zhangdeman/network/util"
2022-06-25 23:21:02 +08:00
"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) {
2024-07-23 18:29:31 +08:00
httpHandleConfig := define.GetHttpHandleConfig()
2022-06-25 23:21:02 +08:00
traceID := getTraceID(ctx)
requestID := getRequestID(ctx, traceID)
2024-07-23 18:29:31 +08:00
ctx.Set(httpHandleConfig.TraceIDField, traceID)
ctx.Set(httpHandleConfig.RequestIDField, requestID)
ctx.Set(httpHandleConfig.StartRequestTimeField, time.Now())
2022-06-25 23:37:10 +08:00
ctx.Next()
2022-06-25 23:21:02 +08:00
}
}
// 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,
2023-08-10 14:47:20 +08:00
strings.ReplaceAll(networkUtil.IP.GetHostIP(), ".", ""),
strings.ReplaceAll(networkUtil.IP.GetRemoteIP(ctx.Request), ".", ""),
2023-08-26 13:24:25 +08:00
wrapper.StringFromRandom(32, "").Md5().Value,
2022-06-25 23:21:02 +08:00
)
}
// getRequestID 生成requestID
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 23:12 2022/6/25
func getRequestID(ctx *gin.Context, traceID string) string {
2024-07-23 18:29:31 +08:00
requestID := ctx.GetHeader("X-Forward-Request-Id")
2022-06-25 23:21:02 +08:00
if len(requestID) > 0 {
return requestID
}
if len(traceID) > 0 {
return traceID
}
return getTraceID(ctx)
}