From 5a6c2c27df1d47da6f2fa076061db1af1c5e9b0e Mon Sep 17 00:00:00 2001 From: jflyfox Date: Fri, 30 Jul 2021 17:17:13 +0800 Subject: [PATCH] inject Request object into context --- net/ghttp/ghttp_request.go | 6 ++++++ net/ghttp/ghttp_request_middleware.go | 5 +---- net/ghttp/ghttp_unit_router_handler_extended_test.go | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/net/ghttp/ghttp_request.go b/net/ghttp/ghttp_request.go index e01dc1ac8..5aac73d46 100644 --- a/net/ghttp/ghttp_request.go +++ b/net/ghttp/ghttp_request.go @@ -78,6 +78,12 @@ func newRequest(s *Server, r *http.Request, w http.ResponseWriter) *Request { Response: newResponse(s, w), EnterTime: gtime.TimestampMilli(), } + // Inject Request object into context. + request.context = context.WithValue( + request.Context(), + ctxKeyForRequest, + request, + ) request.Cookie = GetCookie(request) request.Session = s.sessionManager.New( r.Context(), diff --git a/net/ghttp/ghttp_request_middleware.go b/net/ghttp/ghttp_request_middleware.go index 11638ddb2..ff8c5a539 100644 --- a/net/ghttp/ghttp_request_middleware.go +++ b/net/ghttp/ghttp_request_middleware.go @@ -7,7 +7,6 @@ package ghttp import ( - "context" "github.com/gogf/gf/errors/gerror" "net/http" "reflect" @@ -130,9 +129,7 @@ func (m *middleware) callHandlerFunc(funcInfo handlerFuncInfo) { funcInfo.Func(m.request) } else { var inputValues = []reflect.Value{ - reflect.ValueOf(context.WithValue( - m.request.Context(), ctxKeyForRequest, m.request, - )), + reflect.ValueOf(m.request.Context()), } if funcInfo.Type.NumIn() == 2 { var ( diff --git a/net/ghttp/ghttp_unit_router_handler_extended_test.go b/net/ghttp/ghttp_unit_router_handler_extended_test.go index 77d50c8f2..49f00095c 100644 --- a/net/ghttp/ghttp_unit_router_handler_extended_test.go +++ b/net/ghttp/ghttp_unit_router_handler_extended_test.go @@ -77,6 +77,6 @@ func Test_Router_Handler_Extended_Handler_WithObject(t *testing.T) { client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) t.Assert(client.GetContent("/test?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18,"Name":"john"}}`) - t.Assert(client.GetContent("/test/error"), `{"code":50,"message":"error","data":null}`) + t.Assert(client.GetContent("/test/error"), `{"code":52,"message":"error","data":null}`) }) }