gopkg/gin/middleware/init_request.go

55 lines
1.7 KiB
Go
Raw Normal View History

2021-03-09 18:08:43 +08:00
// Package middleware...
//
// Description : middleware...
//
2021-07-25 19:05:59 +08:00
// Author : go_developer@163.com<白茶清欢>
2021-03-09 18:08:43 +08:00
//
// Date : 2021-03-09 5:52 下午
package middleware
import (
"time"
2021-07-25 18:50:56 +08:00
commonUtil "git.zhangdeman.cn/zhangdeman/gopkg/util"
2021-03-09 18:08:43 +08:00
"github.com/gin-gonic/gin"
)
// InitRequest 初始化请求信息,统一设置请求时间/请求ID等信息
//
2021-07-25 19:05:59 +08:00
// Author : go_developer@163.com<白茶清欢>
2021-03-09 18:08:43 +08:00
//
// Date : 5:53 下午 2021/3/9
2022-01-13 21:53:05 +08:00
func InitRequest(startTimeField string, traceIDField string) gin.HandlerFunc {
2021-03-09 18:08:43 +08:00
return func(ctx *gin.Context) {
// 设置请求开始时间
2022-01-13 21:53:05 +08:00
if len(startTimeField) == 0 {
startTimeField = "start_time"
}
if len(traceIDField) == 0 {
traceIDField = "trace_id"
}
ctx.Set(startTimeField, time.Now().Unix())
2021-03-09 18:08:43 +08:00
// 设置请求trace_id
2022-01-13 21:53:05 +08:00
ctx.Set(traceIDField, commonUtil.GetHostIP()+"-"+ctx.ClientIP()+"-"+time.Now().Format("20060102150405")+"-"+commonUtil.Md5(commonUtil.GenRandomString("", 16)))
ctx.Next()
}
}
// SupportCross 支持跨域
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 9:40 PM 2022/1/13
func SupportCross(header map[string]string) gin.HandlerFunc {
return func(ctx *gin.Context) {
ctx.Writer.Header().Set("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, Admin-User-Token, admin-user-token")
ctx.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方
ctx.Header("Access-Control-Expose-Headers", "admin-user-token, Admin-User-Token, Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
for key, val := range header {
ctx.Header(key, val)
}
2021-03-09 18:08:43 +08:00
ctx.Next()
}
}