From 409120f77d17e3c1d5762c098d83d6810f9269b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 13 Jan 2022 21:53:05 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0gin=20middleware?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gin/middleware/init_request.go | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/gin/middleware/init_request.go b/gin/middleware/init_request.go index b317e6a..f489d01 100644 --- a/gin/middleware/init_request.go +++ b/gin/middleware/init_request.go @@ -19,12 +19,36 @@ import ( // Author : go_developer@163.com<白茶清欢> // // Date : 5:53 下午 2021/3/9 -func InitRequest() func(ctx *gin.Context) { +func InitRequest(startTimeField string, traceIDField string) gin.HandlerFunc { return func(ctx *gin.Context) { // 设置请求开始时间 - ctx.Set("start_time", time.Now().Unix()) + if len(startTimeField) == 0 { + startTimeField = "start_time" + } + if len(traceIDField) == 0 { + traceIDField = "trace_id" + } + ctx.Set(startTimeField, time.Now().Unix()) // 设置请求trace_id - ctx.Set("trace_id", time.Now().Format("20060102150405")+"+"+commonUtil.GetHostIP()+"-"+commonUtil.Md5(commonUtil.GenRandomString("", 16))) + 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) + } ctx.Next() } }