From 8b1086ad56011e0e65f80f644bbbe5432674319f Mon Sep 17 00:00:00 2001 From: seasrain <99347745@qq.com> Date: Fri, 10 Sep 2021 21:44:41 +0800 Subject: [PATCH] fix: optimizate with context (#1460) * fix: optimizate with context --- transport/http/server.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/transport/http/server.go b/transport/http/server.go index 8265aeef3..a8c5513a3 100644 --- a/transport/http/server.go +++ b/transport/http/server.go @@ -181,12 +181,17 @@ func (s *Server) ServeHTTP(res http.ResponseWriter, req *http.Request) { func (s *Server) filter() mux.MiddlewareFunc { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() + var ( + ctx context.Context + cancel context.CancelFunc + ) if s.timeout > 0 { - ctx, cancel = context.WithTimeout(ctx, s.timeout) - defer cancel() + ctx, cancel = context.WithTimeout(req.Context(), s.timeout) + } else { + ctx, cancel = context.WithCancel(req.Context()) } + defer cancel() + pathTemplate := req.URL.Path if route := mux.CurrentRoute(req); route != nil { // /path/123 -> /path/{id}