From 9eb3b92c41c05b9bb2f2b7afb53df0a3989d222c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Jul 2024 16:40:13 +0800 Subject: [PATCH 01/11] =?UTF-8?q?=E5=A2=9E=E5=8A=A0wrapper=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- request/wrapper.go | 72 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/request/wrapper.go b/request/wrapper.go index 1cdc62a..9efc290 100644 --- a/request/wrapper.go +++ b/request/wrapper.go @@ -119,3 +119,75 @@ func (wh *wrapperHandle) GetContentType(ctx *gin.Context, defaultVal string) str func (wh *wrapperHandle) GetResponseBody(ctx *gin.Context, defaultVal string) string { return "" } + +// GetClientIp 获取请求客户端IP +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:31 2024/7/23 +func (wh *wrapperHandle) GetClientIp(ctx *gin.Context, defaultVal string) string { + if nil == ctx { + return defaultVal + } + return ctx.ClientIP() +} + +// GetUserAgent 获取user_agent +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:32 2024/7/23 +func (wh *wrapperHandle) GetUserAgent(ctx *gin.Context, defaultVal string) string { + if nil == ctx { + return defaultVal + } + return ctx.Request.UserAgent() +} + +// GetCtxData 获取请求上下文数据 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:35 2024/7/23 +func (wh *wrapperHandle) GetCtxData(ctx *gin.Context, key string, defaultVal any) any { + if nil == ctx { + return defaultVal + } + if val, exist := ctx.Get(key); !exist || nil == val { + return defaultVal + } else { + return val + } +} + +// GetCtxStringData 获取字符串数据 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:37 2024/7/23 +func (wh *wrapperHandle) GetCtxStringData(ctx *gin.Context, key string, defaultVal string) string { + if nil == ctx { + return defaultVal + } + val := ctx.GetString(key) + if len(val) == 0 { + return defaultVal + } + return val +} + +// GetCtxIntData 获取int数据 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:39 2024/7/23 +func (wh *wrapperHandle) GetCtxIntData(ctx *gin.Context, key string, defaultVal int64) int64 { + if nil == ctx { + return defaultVal + } + val := wh.GetCtxData(ctx, key, nil) + if nil == val { + return defaultVal + } + return ctx.GetInt64(key) +} From ca0cb31235d0cc0788d2dc39f421af8a1067e286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Jul 2024 17:09:29 +0800 Subject: [PATCH 02/11] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=93=8D=E5=BA=94?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- define/response.go | 119 ++++++++++++++++++++++--------------------- go.mod | 2 +- go.sum | 2 + request/wrapper.go | 2 +- response/response.go | 16 +++--- 5 files changed, 73 insertions(+), 68 deletions(-) diff --git a/define/response.go b/define/response.go index 82076bd..3b4e84f 100644 --- a/define/response.go +++ b/define/response.go @@ -7,31 +7,13 @@ // Date : 2022-06-25 20:33 package define +import ( + "git.zhangdeman.cn/zhangdeman/consts" + "git.zhangdeman.cn/zhangdeman/wrapper" +) + var ( - // RequestIDField 请求ID - RequestIDField = "request_id" - // TraceIDField 追踪ID - TraceIDField = "trace_id" - // StartRequestTimeField 开始请求时间字段 - StartRequestTimeField = "start_request_time" - // FinishRequestTimeField 完成请求时间 - FinishRequestTimeField = "finish_request_time" - // ResponseCodeField 响应状态码字段 - ResponseCodeField = "code" - // ResponseMessageField 响应信息字段 - ResponseMessageField = "message" - // HandleRequestCostField 处理请求耗时 - HandleRequestCostField = "cost" - // ResponseDataField 响应数据字段 - ResponseDataField = "data" - // ResponseTraceIDField 响应TraceID字段 - ResponseTraceIDField = "trace_id" - // ResponseRequestIDField 响应的请求ID字段 - ResponseRequestIDField = "request_id" - // RecordResponseDataField 记录响应数据到上下文 - RecordResponseDataField = "pkg_gin_record_response_data" - // RecordRequestDataField 记录请求数据到上下文 - RecordRequestDataField = "pkg_gin_record_request_data" + inputHttpHandleConfig *HttpHandleConfig ) // HttpHandleConfig 请求处理配置 @@ -47,8 +29,8 @@ type HttpHandleConfig struct { HandleRequestCostField string ResponseDataField string ResponseTraceIDField string - ResponseRequestIDField string StartRequestTimeField string + FinishRequestTimeField string } // ConvertDefaultConfig 覆盖默认配置 @@ -57,39 +39,60 @@ type HttpHandleConfig struct { // // Date : 20:41 2022/6/25 func ConvertDefaultConfig(cfg *HttpHandleConfig) { - if len(cfg.RequestIDField) > 0 { - RequestIDField = cfg.ResponseRequestIDField - } + inputHttpHandleConfig = cfg +} - if len(cfg.TraceIDField) > 0 { - TraceIDField = cfg.TraceIDField - } - - if len(cfg.ResponseCodeField) > 0 { - ResponseCodeField = cfg.ResponseCodeField - } - - if len(cfg.ResponseMessageField) > 0 { - ResponseMessageField = cfg.ResponseMessageField - } - - if len(cfg.ResponseDataField) > 0 { - ResponseDataField = cfg.ResponseDataField - } - - if len(cfg.ResponseRequestIDField) > 0 { - ResponseRequestIDField = cfg.ResponseRequestIDField - } - - if len(cfg.ResponseTraceIDField) > 0 { - ResponseTraceIDField = cfg.ResponseTraceIDField - } - - if len(cfg.HandleRequestCostField) > 0 { - HandleRequestCostField = cfg.HandleRequestCostField - } - - if len(cfg.StartRequestTimeField) > 0 { - StartRequestTimeField = cfg.StartRequestTimeField +// GetHttpHandleConfig 获取http配置 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:55 2024/7/23 +func GetHttpHandleConfig() *HttpHandleConfig { + return &HttpHandleConfig{ + RequestIDField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.RequestIDField == "", + consts.GinRequestIDField, + wrapper.String(inputHttpHandleConfig.RequestIDField), + ).Value(), + TraceIDField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.TraceIDField == "", + consts.GinTraceIDField, + wrapper.String(inputHttpHandleConfig.TraceIDField), + ).Value(), + ResponseCodeField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.ResponseCodeField == "", + consts.GinResponseCodeField, + wrapper.String(inputHttpHandleConfig.ResponseCodeField), + ).Value(), + ResponseMessageField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.ResponseMessageField == "", + consts.GinResponseMessageField, + wrapper.String(inputHttpHandleConfig.ResponseMessageField), + ).Value(), + HandleRequestCostField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.HandleRequestCostField == "", + consts.GinHandleRequestCostField, + wrapper.String(inputHttpHandleConfig.HandleRequestCostField), + ).Value(), + ResponseDataField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.ResponseDataField == "", + consts.GinResponseDataField, + wrapper.String(inputHttpHandleConfig.ResponseDataField), + ).Value(), + ResponseTraceIDField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.ResponseTraceIDField == "", + consts.GinResponseTraceIDField, + wrapper.String(inputHttpHandleConfig.ResponseTraceIDField), + ).Value(), + StartRequestTimeField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.StartRequestTimeField == "", + consts.GinStartRequestTimeField, + wrapper.String(inputHttpHandleConfig.StartRequestTimeField), + ).Value(), + FinishRequestTimeField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.FinishRequestTimeField == "", + consts.GinFinishRequestTimeField, + wrapper.String(inputHttpHandleConfig.FinishRequestTimeField), + ).Value(), } } diff --git a/go.mod b/go.mod index 3f808f8..8d6196a 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,7 @@ require ( ) require ( - git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240719075638-afb5d1d933ce // indirect + git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240723085016-ee0510753552 // indirect git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211 // indirect git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0 // indirect git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240618035451-8d48a6bd39dd // indirect diff --git a/go.sum b/go.sum index 0a7c671..4e0f061 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240719075638-afb5d1d933ce h1:DH01rT/F/UNMqXm5HIv+Q2oKPSkg8rjy1TK8pE83rpU= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240719075638-afb5d1d933ce/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= +git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240723085016-ee0510753552 h1:SgxcaLXEXn3ImMOik9y3xDz82KwK/+9IhqV1kZbqIwQ= +git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240723085016-ee0510753552/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211 h1:I/wOsRpCSRkU9vo1u703slQsmK0wnNeZzsWQOGtIAG0= git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211/go.mod h1:SrtvrQRdzt+8KfYzvosH++gWxo2ShPTzR1m3VQ6uX7U= git.zhangdeman.cn/zhangdeman/exception v0.0.0-20231105153815-e8561a060cc8 h1:q9pXs8ByVg/XwyDopIGyfEOi/LyHFR0r1rCnJ90uFxw= diff --git a/request/wrapper.go b/request/wrapper.go index 9efc290..b1b4620 100644 --- a/request/wrapper.go +++ b/request/wrapper.go @@ -1,4 +1,4 @@ -// Package gin ... +// Package request ... // // Description : gin ... // diff --git a/response/response.go b/response/response.go index e8b35b9..4acf36c 100644 --- a/response/response.go +++ b/response/response.go @@ -43,18 +43,18 @@ func Send(ctx *gin.Context, code interface{}, httpCode int, data interface{}) { } // 设置数据已发送的标识 defer ctx.Set(hasSendResponseFlag, true) + responseConfig := define.GetHttpHandleConfig() finishRequestTime := time.Now() responseData := map[string]interface{}{ - define.ResponseCodeField: code, - define.ResponseMessageField: exception.GetMessage(code), - define.ResponseTraceIDField: ctx.GetString(define.TraceIDField), - define.ResponseRequestIDField: ctx.GetString(define.RequestIDField), - define.ResponseDataField: data, - define.HandleRequestCostField: finishRequestTime.UnixMilli() - ctx.GetTime(define.StartRequestTimeField).UnixMilli(), + responseConfig.ResponseCodeField: code, + responseConfig.ResponseMessageField: exception.GetMessage(code), + responseConfig.ResponseTraceIDField: ctx.GetString(responseConfig.ResponseTraceIDField), + responseConfig.ResponseDataField: data, + responseConfig.HandleRequestCostField: finishRequestTime.UnixMilli() - ctx.GetTime(responseConfig.StartRequestTimeField).UnixMilli(), } // 记录完成时间 - ctx.Set(define.FinishRequestTimeField, finishRequestTime) - ctx.Set(define.RecordResponseDataField, responseData) + ctx.Set(responseConfig.FinishRequestTimeField, finishRequestTime) + ctx.Set(responseConfig.ResponseDataField, responseData) responseException := exception.New(code, httpCode, responseData) ctx.JSON(responseException.GetHttpCode(), responseException.GetData()) } From 20d655973aac3b0203ca5fafd1e77ec4825d0d9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Jul 2024 18:29:31 +0800 Subject: [PATCH 03/11] =?UTF-8?q?=E4=BF=AE=E5=A4=8DinitRequest=20middlewar?= =?UTF-8?q?e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/init_request.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/middleware/init_request.go b/middleware/init_request.go index 0b12a34..4645eca 100644 --- a/middleware/init_request.go +++ b/middleware/init_request.go @@ -27,11 +27,12 @@ import ( // 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(define.TraceIDField, traceID) - ctx.Set(define.RequestIDField, requestID) - ctx.Set(define.StartRequestTimeField, time.Now()) + ctx.Set(httpHandleConfig.TraceIDField, traceID) + ctx.Set(httpHandleConfig.RequestIDField, requestID) + ctx.Set(httpHandleConfig.StartRequestTimeField, time.Now()) ctx.Next() } } @@ -57,7 +58,7 @@ func getTraceID(ctx *gin.Context) string { // // Date : 23:12 2022/6/25 func getRequestID(ctx *gin.Context, traceID string) string { - requestID := ctx.GetHeader("X-Forward-Request-ID") + requestID := ctx.GetHeader("X-Forward-Request-Id") if len(requestID) > 0 { return requestID } From 8f533f5b04625371c5c70ab3b31c28b11b09acde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Jul 2024 21:34:40 +0800 Subject: [PATCH 04/11] fix --- define/response.go | 30 +++++++++++++++++++++--------- middleware/access_log.go | 23 +++++++++++++---------- 2 files changed, 34 insertions(+), 19 deletions(-) diff --git a/define/response.go b/define/response.go index 3b4e84f..ac53487 100644 --- a/define/response.go +++ b/define/response.go @@ -22,15 +22,17 @@ var ( // // Date : 20:41 2022/6/25 type HttpHandleConfig struct { - RequestIDField string - TraceIDField string - ResponseCodeField string - ResponseMessageField string - HandleRequestCostField string - ResponseDataField string - ResponseTraceIDField string - StartRequestTimeField string - FinishRequestTimeField string + RecordRequestDataField string + RecordResponseDataField string + RequestIDField string + TraceIDField string + ResponseCodeField string + ResponseMessageField string + HandleRequestCostField string + ResponseDataField string + ResponseTraceIDField string + StartRequestTimeField string + FinishRequestTimeField string } // ConvertDefaultConfig 覆盖默认配置 @@ -94,5 +96,15 @@ func GetHttpHandleConfig() *HttpHandleConfig { consts.GinFinishRequestTimeField, wrapper.String(inputHttpHandleConfig.FinishRequestTimeField), ).Value(), + RecordRequestDataField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.RecordRequestDataField == "", + consts.GinRecordRequestDataField, + wrapper.String(inputHttpHandleConfig.RecordRequestDataField), + ).Value(), + RecordResponseDataField: wrapper.TernaryOperator.String( + nil == inputHttpHandleConfig || inputHttpHandleConfig.RecordResponseDataField == "", + consts.GinRecordResponseDataField, + wrapper.String(inputHttpHandleConfig.RecordResponseDataField), + ).Value(), } } diff --git a/middleware/access_log.go b/middleware/access_log.go index c30f118..d6a6c3a 100644 --- a/middleware/access_log.go +++ b/middleware/access_log.go @@ -8,9 +8,10 @@ package middleware import ( - "git.zhangdeman.cn/zhangdeman/wrapper" "strings" + "git.zhangdeman.cn/zhangdeman/wrapper" + "git.zhangdeman.cn/zhangdeman/gin/define" "github.com/gin-gonic/gin" @@ -41,7 +42,8 @@ func fillCfg(cfg *AccessConfig) { if nil == cfg.ExtraFieldList { cfg.ExtraFieldList = make([]string, 0) } - cfg.ExtraFieldList = append(cfg.ExtraFieldList, define.RecordRequestDataField, define.RecordResponseDataField) + handleConfig := define.GetHttpHandleConfig() + cfg.ExtraFieldList = append(cfg.ExtraFieldList, handleConfig.RecordRequestDataField, handleConfig.RecordResponseDataField) } // getLogRequestHeader 获取记录的请求header @@ -54,7 +56,7 @@ func getLogRequestHeader(ctx *gin.Context, cfg *AccessConfig) map[string][]strin headerTable := make(map[string][]string) if len(cfg.RequestHeaderList) == 0 { // 全部记录 - for headerKey, _ := range ctx.Request.Header { + for headerKey := range ctx.Request.Header { cfg.RequestHeaderList = append(cfg.RequestHeaderList, headerKey) } } @@ -74,7 +76,7 @@ func getLogResponseHeader(ctx *gin.Context, cfg *AccessConfig) map[string][]stri responseHeaderTable := make(map[string][]string) if len(cfg.ResponseHeaderList) == 0 { // 全部记录 - for headerKey, _ := range ctx.Writer.Header() { + for headerKey := range ctx.Writer.Header() { cfg.ResponseHeaderList = append(cfg.ResponseHeaderList, headerKey) } zap.Any("pkg_gin_response_header", ctx.Writer.Header()) @@ -92,6 +94,7 @@ func getLogResponseHeader(ctx *gin.Context, cfg *AccessConfig) map[string][]stri // Date : 10:55 2022/7/14 func LogRequest(cfg *AccessConfig) gin.HandlerFunc { fillCfg(cfg) + handleConfig := define.GetHttpHandleConfig() return func(ctx *gin.Context) { // 未传入配置或者未传入日志实例 if nil == cfg || nil == cfg.Logger || !cfg.IsRecordLog(ctx) { @@ -99,16 +102,16 @@ func LogRequest(cfg *AccessConfig) gin.HandlerFunc { return } ctx.Next() - startRequestTime := wrapper.OwnTime(ctx.GetTime(define.StartRequestTimeField)) + startRequestTime := wrapper.OwnTime(ctx.GetTime(handleConfig.StartRequestTimeField)) logDataList := []zap.Field{ // 开始请求时间 - zap.Any(define.StartRequestTimeField, startRequestTime.FormatUnixMilli()), + zap.Any(handleConfig.StartRequestTimeField, startRequestTime.FormatUnixMilli()), } // 结束时间 - finishRequestTime := wrapper.OwnTime(ctx.GetTime(define.FinishRequestTimeField)) + finishRequestTime := wrapper.OwnTime(ctx.GetTime(handleConfig.FinishRequestTimeField)) logDataList = append( logDataList, - zap.Any(define.FinishRequestTimeField, finishRequestTime.FormatUnixMilli()), // 请求完成时间 + zap.Any(handleConfig.FinishRequestTimeField, finishRequestTime.FormatUnixMilli()), // 请求完成时间 zap.Int64("pkg_gin_request_cost", finishRequestTime.UnixMilli()-startRequestTime.UnixMilli()), // 接口耗时 zap.Any("pkg_gin_request_header", getLogRequestHeader(ctx, cfg)), // 请求header zap.Any("pkg_gin_response_header", getLogResponseHeader(ctx, cfg)), // 响应header @@ -126,8 +129,8 @@ func LogRequest(cfg *AccessConfig) gin.HandlerFunc { // hook 不为nil, 自动触发 cfg.FinishHook( ctx, - []byte(ctx.GetString(define.RecordRequestDataField)), - ctx.GetStringMap(define.RecordResponseDataField), + []byte(ctx.GetString(handleConfig.RecordRequestDataField)), + ctx.GetStringMap(handleConfig.RecordResponseDataField), finishRequestTime.UnixMilli()-startRequestTime.UnixMilli(), ) From a1418c290cd21b7703ce7dec2d2dffdb74a3b3f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Jul 2024 21:40:53 +0800 Subject: [PATCH 05/11] fix --- request/form.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/request/form.go b/request/form.go index 7306c04..14d4971 100644 --- a/request/form.go +++ b/request/form.go @@ -10,6 +10,7 @@ package request import ( "bytes" "errors" + "io" "io/ioutil" "net/http" "strings" @@ -36,10 +37,10 @@ type form struct { // // Date : 00:34 2022/7/3 func (f *form) Parse(ctx *gin.Context, receiver interface{}) error { - - requestBody, _ := ioutil.ReadAll(ctx.Request.Body) + handleConfig := define.GetHttpHandleConfig() + requestBody, _ := io.ReadAll(ctx.Request.Body) // 请求信息写入上下文 - ctx.Set(define.RecordRequestDataField, string(requestBody)) + ctx.Set(handleConfig.RecordRequestDataField, string(requestBody)) // 因为请求体被读一遍之后就没了,重新赋值 requestBody ctx.Request.Body = ioutil.NopCloser(bytes.NewReader(requestBody)) method := strings.ToUpper(ctx.Request.Method) From 86cecc4eb707b4e12d28094ec1f4cb55f7b664af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Jul 2024 21:53:00 +0800 Subject: [PATCH 06/11] init --- define/response.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/define/response.go b/define/response.go index ac53487..b774eef 100644 --- a/define/response.go +++ b/define/response.go @@ -13,7 +13,7 @@ import ( ) var ( - inputHttpHandleConfig *HttpHandleConfig + inputHttpHandleConfig = &HttpHandleConfig{} ) // HttpHandleConfig 请求处理配置 From 3368418b3b6d23372fac663cc9600077a53b7092 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 26 Jul 2024 11:07:14 +0800 Subject: [PATCH 07/11] update go mod --- go.mod | 2 +- go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 8d6196a..854f429 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.21 toolchain go1.21.5 require ( + git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240726024939-e424db29c5c4 git.zhangdeman.cn/zhangdeman/exception v0.0.0-20231105153815-e8561a060cc8 git.zhangdeman.cn/zhangdeman/network v0.0.0-20230925112156-f0eb86dd2442 git.zhangdeman.cn/zhangdeman/wrapper v0.0.0-20240627031706-9ff1c213bb50 @@ -16,7 +17,6 @@ require ( ) require ( - git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240723085016-ee0510753552 // indirect git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211 // indirect git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0 // indirect git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240618035451-8d48a6bd39dd // indirect diff --git a/go.sum b/go.sum index 4e0f061..e72ca89 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240719075638-afb5d1d933ce h1:DH01rT git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240719075638-afb5d1d933ce/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240723085016-ee0510753552 h1:SgxcaLXEXn3ImMOik9y3xDz82KwK/+9IhqV1kZbqIwQ= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240723085016-ee0510753552/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= +git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240726024939-e424db29c5c4 h1:mibnyzYbZullK0aTHVASHl3UeoVr8IgytQZsuyv+yEM= +git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240726024939-e424db29c5c4/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211 h1:I/wOsRpCSRkU9vo1u703slQsmK0wnNeZzsWQOGtIAG0= git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211/go.mod h1:SrtvrQRdzt+8KfYzvosH++gWxo2ShPTzR1m3VQ6uX7U= git.zhangdeman.cn/zhangdeman/exception v0.0.0-20231105153815-e8561a060cc8 h1:q9pXs8ByVg/XwyDopIGyfEOi/LyHFR0r1rCnJ90uFxw= From 3c29aa847c8f145b3b875988a0e599739459f673 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 26 Jul 2024 11:50:42 +0800 Subject: [PATCH 08/11] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=8E=B7=E5=8F=96query?= =?UTF-8?q?=E5=92=8Cbody=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 7 +++++++ go.sum | 17 ++++++++++++++++ request/wrapper.go | 49 +++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 854f429..e2e0101 100644 --- a/go.mod +++ b/go.mod @@ -17,10 +17,13 @@ require ( ) require ( + git.zhangdeman.cn/zhangdeman/easylock v0.0.0-20230731062340-983985c12eda // indirect git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211 // indirect + git.zhangdeman.cn/zhangdeman/logger v0.0.0-20240725055115-98eb52ae307a // indirect git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0 // indirect git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240618035451-8d48a6bd39dd // indirect git.zhangdeman.cn/zhangdeman/util v0.0.0-20240618042405-6ee2c904644e // indirect + git.zhangdeman.cn/zhangdeman/websocket v0.0.0-20240723075210-85feada512b2 // indirect github.com/BurntSushi/toml v1.4.0 // indirect github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 // indirect github.com/bytedance/sonic v1.11.9 // indirect @@ -35,9 +38,12 @@ require ( github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/goccy/go-json v0.10.3 // indirect + github.com/gorilla/websocket v1.5.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.8 // indirect github.com/leodido/go-urn v1.4.0 // indirect + github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible // indirect + github.com/lestrrat-go/strftime v1.0.6 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect @@ -59,5 +65,6 @@ require ( golang.org/x/sys v0.22.0 // indirect golang.org/x/text v0.16.0 // indirect google.golang.org/protobuf v1.34.2 // indirect + gopkg.in/olahol/melody.v1 v1.0.0-20170518105555-d52139073376 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index e72ca89..e55f91f 100644 --- a/go.sum +++ b/go.sum @@ -4,10 +4,14 @@ git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240723085016-ee0510753552 h1:SgxcaL git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240723085016-ee0510753552/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240726024939-e424db29c5c4 h1:mibnyzYbZullK0aTHVASHl3UeoVr8IgytQZsuyv+yEM= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240726024939-e424db29c5c4/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= +git.zhangdeman.cn/zhangdeman/easylock v0.0.0-20230731062340-983985c12eda h1:bMD6r9gjRy7cO+T4zRQVYAesgIblBdTnhzT1vN5wjvI= +git.zhangdeman.cn/zhangdeman/easylock v0.0.0-20230731062340-983985c12eda/go.mod h1:dT0rmHcJ9Z9IqWeMIt7YzR88nKkNV2V3dfG0j9Q6lK0= git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211 h1:I/wOsRpCSRkU9vo1u703slQsmK0wnNeZzsWQOGtIAG0= git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211/go.mod h1:SrtvrQRdzt+8KfYzvosH++gWxo2ShPTzR1m3VQ6uX7U= git.zhangdeman.cn/zhangdeman/exception v0.0.0-20231105153815-e8561a060cc8 h1:q9pXs8ByVg/XwyDopIGyfEOi/LyHFR0r1rCnJ90uFxw= git.zhangdeman.cn/zhangdeman/exception v0.0.0-20231105153815-e8561a060cc8/go.mod h1:Voc8J4ordx7nuMWpgACXXZULQy7ZIuBzcEIoS8VnDIw= +git.zhangdeman.cn/zhangdeman/logger v0.0.0-20240725055115-98eb52ae307a h1:22VkxGmpS58zHA8tf75lPr/3S6hmHKP00w/jUa700Ps= +git.zhangdeman.cn/zhangdeman/logger v0.0.0-20240725055115-98eb52ae307a/go.mod h1:phaF6LMebn7Fpp8J/mOzHRYGniKuCk78k4N53T2m8NI= git.zhangdeman.cn/zhangdeman/network v0.0.0-20230925112156-f0eb86dd2442 h1:1eBf0C0gdpBQOqjTK3UCw/mwzQ/SCodx3iTQtidx9eE= git.zhangdeman.cn/zhangdeman/network v0.0.0-20230925112156-f0eb86dd2442/go.mod h1:hFYWiS+ExIuJJJdwHWy4P3pVHbd/0mpv53qlbhDNdTI= git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0 h1:gUDlQMuJ4xNfP2Abl1Msmpa3fASLWYkNlqDFF/6GN0Y= @@ -16,6 +20,8 @@ git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240618035451-8d48a6bd39dd h1:2Y3 git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240618035451-8d48a6bd39dd/go.mod h1:6+7whkCmb4sJDIfH3HxNuXRveaM0gCCNWd2uXZqNtIE= git.zhangdeman.cn/zhangdeman/util v0.0.0-20240618042405-6ee2c904644e h1:Q973S6CcWr1ICZhFI1STFOJ+KUImCl2BaIXm6YppBqI= git.zhangdeman.cn/zhangdeman/util v0.0.0-20240618042405-6ee2c904644e/go.mod h1:VpPjBlwz8U+OxZuxzHQBv1aEEZ3pStH6bZvT21ADEbI= +git.zhangdeman.cn/zhangdeman/websocket v0.0.0-20240723075210-85feada512b2 h1:P2kuhU2TFWk9mPbJlZCK6FMDVS7S3NGafWKD4eNqKiI= +git.zhangdeman.cn/zhangdeman/websocket v0.0.0-20240723075210-85feada512b2/go.mod h1:7KaMpQmWgiNLpEkaV7oDtep7geI1f/VoCoPVcyvMjAE= git.zhangdeman.cn/zhangdeman/wrapper v0.0.0-20240627031706-9ff1c213bb50 h1:olo34i2Gq5gX7bYPv5TR4X5l5CrYFtu9UCElkYlmL2c= git.zhangdeman.cn/zhangdeman/wrapper v0.0.0-20240627031706-9ff1c213bb50/go.mod h1:US/pcq2vstE3iyxIHf53w8IeXKkZys7bj/ozLWkRYeE= github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= @@ -33,6 +39,8 @@ github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1 h1:CaO/zOnF8VvUfEbhRatPcwKVWamvbYd8tQGRWacE9kU= github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1/go.mod h1:+hnT3ywWDTAFrW5aE+u2Sa/wT555ZqwoCS+pk3p6ry4= github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I= @@ -56,6 +64,8 @@ github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PU github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= @@ -64,6 +74,11 @@ github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZY github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is= +github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4= +github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA= +github.com/lestrrat-go/strftime v1.0.6 h1:CFGsDEt1pOpFNU+TJB0nhz9jl+K0hZSLE205AhTIGQQ= +github.com/lestrrat-go/strftime v1.0.6/go.mod h1:f7jQKgV5nnJpYgdEasS+/y7EsTb8ykN2z68n3TtcTaw= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= @@ -133,6 +148,8 @@ google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6h google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/olahol/melody.v1 v1.0.0-20170518105555-d52139073376 h1:sY2a+y0j4iDrajJcorb+a0hJIQ6uakU5gybjfLWHlXo= +gopkg.in/olahol/melody.v1 v1.0.0-20170518105555-d52139073376/go.mod h1:BHKOc1m5wm8WwQkMqYBoo4vNxhmF7xg8+xhG8L+Cy3M= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/request/wrapper.go b/request/wrapper.go index b1b4620..df846f7 100644 --- a/request/wrapper.go +++ b/request/wrapper.go @@ -8,8 +8,11 @@ package request import ( + "bytes" + "git.zhangdeman.cn/zhangdeman/consts" "git.zhangdeman.cn/zhangdeman/wrapper" "github.com/gin-gonic/gin" + "io" "net/url" "strings" ) @@ -79,11 +82,19 @@ func (wh *wrapperHandle) GetScheme(ctx *gin.Context, defaultVal string) string { // Author : go_developer@163.com<白茶清欢> // // Date : 16:03 2024/1/2 -func (wh *wrapperHandle) GetQuery(ctx *gin.Context) url.Values { +func (wh *wrapperHandle) GetQuery(ctx *gin.Context) map[string]string { + query := make(map[string]string) if nil != ctx && nil != ctx.Request && nil != ctx.Request.URL { - return ctx.Request.URL.Query() + for paramName, valueList := range { + if len(valueList) == 0 { + query[paramName] = "" + } else { + query[paramName] = valueList[0] + } + } + return query } - return make(url.Values) + return query } // GetMethod 获取请求方法 @@ -111,6 +122,38 @@ func (wh *wrapperHandle) GetContentType(ctx *gin.Context, defaultVal string) str return wrapper.TernaryOperator.String(len(contentType) > 0, wrapper.String(contentType), wrapper.String(defaultVal)).Value() } +// GetRequestBody 获取请求body +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 11:25 2024/7/26 +func (wh *wrapperHandle) GetRequestBody(ctx *gin.Context) map[string]any { + body := map[string]any{} + contentType := wh.GetContentType(ctx, "") + if strings.Contains(contentType, consts.MimeTypeJson) { // json请求 + data, err := io.ReadAll(ctx.Request.Body) + if nil != err { + return body + } + ctx.Request.Body = io.NopCloser(bytes.NewBuffer(data)) + return body + } + if strings.Contains(contentType, consts.MimeTypeXWWWFormUrlencoded) { // form请求 + if err := ctx.Request.ParseForm(); nil != err { + return body + } + for paramName, itemParam := range ctx.Request.PostForm { + if len(itemParam) > 0 { + body[paramName] = itemParam[0] + } else { + body[paramName] = "" + } + } + return body + } + return body +} + // GetResponseBody 获取响应body // // Author : go_developer@163.com<白茶清欢> From b2fe05111c2d7dc95b98ec3a66ee602600b3a4ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 26 Jul 2024 11:52:53 +0800 Subject: [PATCH 09/11] fix --- request/wrapper.go | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/request/wrapper.go b/request/wrapper.go index df846f7..689f1e1 100644 --- a/request/wrapper.go +++ b/request/wrapper.go @@ -13,7 +13,6 @@ import ( "git.zhangdeman.cn/zhangdeman/wrapper" "github.com/gin-gonic/gin" "io" - "net/url" "strings" ) @@ -85,7 +84,7 @@ func (wh *wrapperHandle) GetScheme(ctx *gin.Context, defaultVal string) string { func (wh *wrapperHandle) GetQuery(ctx *gin.Context) map[string]string { query := make(map[string]string) if nil != ctx && nil != ctx.Request && nil != ctx.Request.URL { - for paramName, valueList := range { + for paramName, valueList := range ctx.Request.URL.Query() { if len(valueList) == 0 { query[paramName] = "" } else { @@ -130,14 +129,6 @@ func (wh *wrapperHandle) GetContentType(ctx *gin.Context, defaultVal string) str func (wh *wrapperHandle) GetRequestBody(ctx *gin.Context) map[string]any { body := map[string]any{} contentType := wh.GetContentType(ctx, "") - if strings.Contains(contentType, consts.MimeTypeJson) { // json请求 - data, err := io.ReadAll(ctx.Request.Body) - if nil != err { - return body - } - ctx.Request.Body = io.NopCloser(bytes.NewBuffer(data)) - return body - } if strings.Contains(contentType, consts.MimeTypeXWWWFormUrlencoded) { // form请求 if err := ctx.Request.ParseForm(); nil != err { return body @@ -151,6 +142,16 @@ func (wh *wrapperHandle) GetRequestBody(ctx *gin.Context) map[string]any { } return body } + + if strings.Contains(contentType, consts.MimeTypeJson) || nil != ctx.Request.Body { // json请求 或者非 json请求 存在 body + data, err := io.ReadAll(ctx.Request.Body) + if nil != err { + return body + } + ctx.Request.Body = io.NopCloser(bytes.NewBuffer(data)) + return body + } + return body } From b9c0389e7bb0380495970240309c67598a529313 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 26 Jul 2024 12:25:22 +0800 Subject: [PATCH 10/11] =?UTF-8?q?=E5=8D=87=E7=BA=A7=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=AE=B0=E5=BD=95=20+=20=E5=8D=87=E7=BA=A7?= =?UTF-8?q?=20request=20wrapperHandle=20+=20=E6=8B=86=E5=88=86after=20hook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/access_log.go | 77 +++++++++++-------------------- middleware/hook_after_response.go | 38 +++++++++++++++ middleware/init_request.go | 2 +- request/wrapper.go | 11 ++++- response/response.go | 4 +- 5 files changed, 78 insertions(+), 54 deletions(-) create mode 100644 middleware/hook_after_response.go diff --git a/middleware/access_log.go b/middleware/access_log.go index d6a6c3a..4411b65 100644 --- a/middleware/access_log.go +++ b/middleware/access_log.go @@ -8,14 +8,15 @@ package middleware import ( + "git.zhangdeman.cn/zhangdeman/consts" + "git.zhangdeman.cn/zhangdeman/gin/request" + "go.uber.org/zap" "strings" - "git.zhangdeman.cn/zhangdeman/wrapper" - "git.zhangdeman.cn/zhangdeman/gin/define" + "git.zhangdeman.cn/zhangdeman/logger" "github.com/gin-gonic/gin" - "go.uber.org/zap" ) // fillCfg 填充默认配置 @@ -30,20 +31,12 @@ func fillCfg(cfg *AccessConfig) { if nil == cfg.IsRecordLog { cfg.IsRecordLog = defaultIsRecordLog } - if nil == cfg.ExtraFieldList { - cfg.ExtraFieldList = make([]string, 0) - } if nil == cfg.RequestHeaderList { cfg.RequestHeaderList = make([]string, 0) } if nil == cfg.ResponseHeaderList { cfg.ResponseHeaderList = make([]string, 0) } - if nil == cfg.ExtraFieldList { - cfg.ExtraFieldList = make([]string, 0) - } - handleConfig := define.GetHttpHandleConfig() - cfg.ExtraFieldList = append(cfg.ExtraFieldList, handleConfig.RecordRequestDataField, handleConfig.RecordResponseDataField) } // getLogRequestHeader 获取记录的请求header @@ -97,43 +90,31 @@ func LogRequest(cfg *AccessConfig) gin.HandlerFunc { handleConfig := define.GetHttpHandleConfig() return func(ctx *gin.Context) { // 未传入配置或者未传入日志实例 - if nil == cfg || nil == cfg.Logger || !cfg.IsRecordLog(ctx) { + if nil == cfg || nil == cfg.Logger || (nil != cfg.IsRecordLog && !cfg.IsRecordLog(ctx)) { ctx.Next() return } + startRequestTime := request.WrapperHandle.GetCtxIntData(ctx, handleConfig.StartRequestTimeField, 0) + // 记录请求日志 + logData := logger.NewLogData(ctx, consts.LogTypeRequest, "", map[string]any{ + handleConfig.StartRequestTimeField: startRequestTime, // 开始请求时间 + "request_header": getLogRequestHeader(ctx, cfg), // 请求header + "request_query": request.WrapperHandle.GetQuery(ctx), // 获取请求query + "request_body": request.WrapperHandle.GetRequestBody(ctx), // 请求body + }) + cfg.Logger.Info("接口请求日志记录", logger.ZapLogDataList(logData)...) ctx.Next() - startRequestTime := wrapper.OwnTime(ctx.GetTime(handleConfig.StartRequestTimeField)) - logDataList := []zap.Field{ - // 开始请求时间 - zap.Any(handleConfig.StartRequestTimeField, startRequestTime.FormatUnixMilli()), - } // 结束时间 - finishRequestTime := wrapper.OwnTime(ctx.GetTime(handleConfig.FinishRequestTimeField)) - logDataList = append( - logDataList, - zap.Any(handleConfig.FinishRequestTimeField, finishRequestTime.FormatUnixMilli()), // 请求完成时间 - zap.Int64("pkg_gin_request_cost", finishRequestTime.UnixMilli()-startRequestTime.UnixMilli()), // 接口耗时 - zap.Any("pkg_gin_request_header", getLogRequestHeader(ctx, cfg)), // 请求header - zap.Any("pkg_gin_response_header", getLogResponseHeader(ctx, cfg)), // 响应header - ) - - // 扩展数据 - for _, field := range cfg.ExtraFieldList { - val, _ := ctx.Get(field) - logDataList = append(logDataList, zap.Any(field, val)) - } - cfg.Logger.Info("请求日志记录", logDataList...) - if nil == cfg.FinishHook { - return - } - // hook 不为nil, 自动触发 - cfg.FinishHook( - ctx, - []byte(ctx.GetString(handleConfig.RecordRequestDataField)), - ctx.GetStringMap(handleConfig.RecordResponseDataField), - finishRequestTime.UnixMilli()-startRequestTime.UnixMilli(), - ) - + finishRequestTime := request.WrapperHandle.GetCtxIntData(ctx, handleConfig.FinishRequestTimeField, 0) + ctx.Set(handleConfig.FinishRequestTimeField, finishRequestTime) + // 记录相应日志 + logResponseData := logger.NewLogData(ctx, consts.LogTypeOutput, "", map[string]any{ + handleConfig.FinishRequestTimeField: finishRequestTime, // 完成请求时间 + "request_cost": finishRequestTime - startRequestTime, // 请求耗时 + "response_body": request.WrapperHandle.GetResponseBody(ctx, handleConfig.ResponseDataField, map[string]any{}), // 响应body + "response_header": getLogResponseHeader(ctx, cfg), // 响应header + }) + cfg.Logger.Info("接口响应日志记录", logger.ZapLogDataList(logResponseData)...) } } @@ -143,12 +124,10 @@ func LogRequest(cfg *AccessConfig) gin.HandlerFunc { // // Date : 11:26 2022/7/14 type AccessConfig struct { - Logger *zap.Logger // 日志实例 - RequestHeaderList []string // 要记录哪些header , 不传全部记录 - ResponseHeaderList []string // 要记录哪些响应header, 不传全部记录 - IsRecordLog func(ctx *gin.Context) bool // 验证当前请求是否记录日志 - ExtraFieldList []string // 记录的扩展字段列表,请将相关数据使用 ctx.Set 写入上下文中, 日志会自动记录 - FinishHook func(ctx *gin.Context, requestData []byte, responseData map[string]interface{}, cost int64) // 请求处理完成之后, 触发的hook函数 + Logger *zap.Logger // 日志实例 + RequestHeaderList []string // 要记录哪些header , 不传全部记录 + ResponseHeaderList []string // 要记录哪些响应header, 不传全部记录 + IsRecordLog func(ctx *gin.Context) bool // 验证当前请求是否记录日志 } // defaultIsRecordLog 默认仅记录 json api 日志 diff --git a/middleware/hook_after_response.go b/middleware/hook_after_response.go new file mode 100644 index 0000000..81a7d5c --- /dev/null +++ b/middleware/hook_after_response.go @@ -0,0 +1,38 @@ +// Package middleware ... +// +// Description : middleware ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2024-07-26 11:54 +package middleware + +import ( + "git.zhangdeman.cn/zhangdeman/gin/define" + "git.zhangdeman.cn/zhangdeman/gin/request" + "github.com/gin-gonic/gin" +) + +type HookFunc func(ctx *gin.Context, requestData []byte, responseData map[string]interface{}, cost int64) + +// HookAfterResponseMiddleware 请求最终处理完成之后执行的中间件 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 11:55 2024/7/26 +func HookAfterResponseMiddleware(ctx *gin.Context, hookFunc HookFunc) gin.HandlerFunc { + handleConfig := define.GetHttpHandleConfig() + return func(ctx *gin.Context) { + ctx.Next() + if nil == hookFunc { + return + } + // hook 不为nil, 自动触发 + hookFunc( + ctx, + []byte(ctx.GetString(handleConfig.RecordRequestDataField)), + ctx.GetStringMap(handleConfig.RecordResponseDataField), + request.WrapperHandle.GetCtxIntData(ctx, handleConfig.StartRequestTimeField, 0)-request.WrapperHandle.GetCtxIntData(ctx, handleConfig.StartRequestTimeField, 0), + ) + } +} diff --git a/middleware/init_request.go b/middleware/init_request.go index 4645eca..61bb406 100644 --- a/middleware/init_request.go +++ b/middleware/init_request.go @@ -32,7 +32,7 @@ func InitRequest() gin.HandlerFunc { requestID := getRequestID(ctx, traceID) ctx.Set(httpHandleConfig.TraceIDField, traceID) ctx.Set(httpHandleConfig.RequestIDField, requestID) - ctx.Set(httpHandleConfig.StartRequestTimeField, time.Now()) + ctx.Set(httpHandleConfig.StartRequestTimeField, time.Now().UnixMilli()) ctx.Next() } } diff --git a/request/wrapper.go b/request/wrapper.go index 689f1e1..67d6dd4 100644 --- a/request/wrapper.go +++ b/request/wrapper.go @@ -160,8 +160,15 @@ func (wh *wrapperHandle) GetRequestBody(ctx *gin.Context) map[string]any { // Author : go_developer@163.com<白茶清欢> // // Date : 15:18 2024/1/2 -func (wh *wrapperHandle) GetResponseBody(ctx *gin.Context, defaultVal string) string { - return "" +func (wh *wrapperHandle) GetResponseBody(ctx *gin.Context, key string, defaultVal any) any { + if nil == ctx { + return defaultVal + } + if val, exist := ctx.Get(key); !exist || nil == val { + return defaultVal + } else { + return val + } } // GetClientIp 获取请求客户端IP diff --git a/response/response.go b/response/response.go index 4acf36c..8eda65e 100644 --- a/response/response.go +++ b/response/response.go @@ -44,13 +44,13 @@ func Send(ctx *gin.Context, code interface{}, httpCode int, data interface{}) { // 设置数据已发送的标识 defer ctx.Set(hasSendResponseFlag, true) responseConfig := define.GetHttpHandleConfig() - finishRequestTime := time.Now() + finishRequestTime := time.Now().UnixMilli() responseData := map[string]interface{}{ responseConfig.ResponseCodeField: code, responseConfig.ResponseMessageField: exception.GetMessage(code), responseConfig.ResponseTraceIDField: ctx.GetString(responseConfig.ResponseTraceIDField), responseConfig.ResponseDataField: data, - responseConfig.HandleRequestCostField: finishRequestTime.UnixMilli() - ctx.GetTime(responseConfig.StartRequestTimeField).UnixMilli(), + responseConfig.HandleRequestCostField: finishRequestTime - ctx.GetTime(responseConfig.StartRequestTimeField).UnixMilli(), } // 记录完成时间 ctx.Set(responseConfig.FinishRequestTimeField, finishRequestTime) From 9b7e714b2932e551ce3492bb52cb0d34d6dd30d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 26 Jul 2024 14:10:47 +0800 Subject: [PATCH 11/11] fix --- middleware/hook_after_response.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/middleware/hook_after_response.go b/middleware/hook_after_response.go index 81a7d5c..f1487a4 100644 --- a/middleware/hook_after_response.go +++ b/middleware/hook_after_response.go @@ -20,7 +20,7 @@ type HookFunc func(ctx *gin.Context, requestData []byte, responseData map[string // Author : go_developer@163.com<白茶清欢> // // Date : 11:55 2024/7/26 -func HookAfterResponseMiddleware(ctx *gin.Context, hookFunc HookFunc) gin.HandlerFunc { +func HookAfterResponseMiddleware(hookFunc HookFunc) gin.HandlerFunc { handleConfig := define.GetHttpHandleConfig() return func(ctx *gin.Context) { ctx.Next()