diff --git a/utils.go b/utils.go index 47106a7a..eaa01528 100644 --- a/utils.go +++ b/utils.go @@ -39,14 +39,14 @@ func Bind(val any) HandlerFunc { // WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware. func WrapF(f http.HandlerFunc) HandlerFunc { return func(c *Context) { - f(c.Writer, c.Request) + f(c.Writer, c.Request.WithContext(c)) } } // WrapH is a helper function for wrapping http.Handler and returns a Gin middleware. func WrapH(h http.Handler) HandlerFunc { return func(c *Context) { - h.ServeHTTP(c.Writer, c.Request) + h.ServeHTTP(c.Writer, c.Request.WithContext(c)) } } diff --git a/utils_test.go b/utils_test.go index 8098c681..be2cc27e 100644 --- a/utils_test.go +++ b/utils_test.go @@ -31,16 +31,23 @@ type testStruct struct { func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) { assert.Equal(t.T, http.MethodPost, req.Method) assert.Equal(t.T, "/path", req.URL.Path) + assert.Equal(t.T, "yes", req.Context().Value("middleware")) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "hello") } func TestWrap(t *testing.T) { router := New() + + router.Use(func(c *Context) { + c.Set("middleware", "yes") + }) + router.POST("/path", WrapH(&testStruct{t})) router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) { assert.Equal(t, http.MethodGet, req.Method) assert.Equal(t, "/path2", req.URL.Path) + assert.Equal(t, "yes", req.Context().Value("middleware")) w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, "hola!") }))