Merge fc2d22c033865e7081a9947ba5de45d1ae3a6f7e into 8763f33c65f7df8be5b9fe7504ab7fcf20abb41d

This commit is contained in:
Ben Visness 2025-03-21 16:49:30 +08:00 committed by GitHub
commit af79adf3ed
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 9 additions and 2 deletions

View File

@ -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))
}
}

View File

@ -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!")
}))