mirror of
https://github.com/gin-gonic/gin.git
synced 2025-04-06 03:57:46 +08:00
Merge fc2d22c033865e7081a9947ba5de45d1ae3a6f7e into 8763f33c65f7df8be5b9fe7504ab7fcf20abb41d
This commit is contained in:
commit
af79adf3ed
4
utils.go
4
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.
|
// WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware.
|
||||||
func WrapF(f http.HandlerFunc) HandlerFunc {
|
func WrapF(f http.HandlerFunc) HandlerFunc {
|
||||||
return func(c *Context) {
|
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.
|
// WrapH is a helper function for wrapping http.Handler and returns a Gin middleware.
|
||||||
func WrapH(h http.Handler) HandlerFunc {
|
func WrapH(h http.Handler) HandlerFunc {
|
||||||
return func(c *Context) {
|
return func(c *Context) {
|
||||||
h.ServeHTTP(c.Writer, c.Request)
|
h.ServeHTTP(c.Writer, c.Request.WithContext(c))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -31,16 +31,23 @@ type testStruct struct {
|
|||||||
func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||||
assert.Equal(t.T, http.MethodPost, req.Method)
|
assert.Equal(t.T, http.MethodPost, req.Method)
|
||||||
assert.Equal(t.T, "/path", req.URL.Path)
|
assert.Equal(t.T, "/path", req.URL.Path)
|
||||||
|
assert.Equal(t.T, "yes", req.Context().Value("middleware"))
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
fmt.Fprint(w, "hello")
|
fmt.Fprint(w, "hello")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWrap(t *testing.T) {
|
func TestWrap(t *testing.T) {
|
||||||
router := New()
|
router := New()
|
||||||
|
|
||||||
|
router.Use(func(c *Context) {
|
||||||
|
c.Set("middleware", "yes")
|
||||||
|
})
|
||||||
|
|
||||||
router.POST("/path", WrapH(&testStruct{t}))
|
router.POST("/path", WrapH(&testStruct{t}))
|
||||||
router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) {
|
router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) {
|
||||||
assert.Equal(t, http.MethodGet, req.Method)
|
assert.Equal(t, http.MethodGet, req.Method)
|
||||||
assert.Equal(t, "/path2", req.URL.Path)
|
assert.Equal(t, "/path2", req.URL.Path)
|
||||||
|
assert.Equal(t, "yes", req.Context().Value("middleware"))
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
fmt.Fprint(w, "hola!")
|
fmt.Fprint(w, "hola!")
|
||||||
}))
|
}))
|
||||||
|
Loading…
x
Reference in New Issue
Block a user