mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-17 05:42:09 +08:00
gin.Context with fallback value from c.Request.Context()
This commit is contained in:
parent
f73c3f3795
commit
ea979c8663
@ -1186,8 +1186,12 @@ func (c *Context) Value(key interface{}) interface{} {
|
|||||||
return c.Request
|
return c.Request
|
||||||
}
|
}
|
||||||
if keyAsString, ok := key.(string); ok {
|
if keyAsString, ok := key.(string); ok {
|
||||||
val, _ := c.Get(keyAsString)
|
if val, exists := c.Get(keyAsString); exists {
|
||||||
return val
|
return val
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
if c.Request == nil || c.Request.Context() == nil {
|
||||||
return nil
|
return nil
|
||||||
|
}
|
||||||
|
return c.Request.Context().Value(key)
|
||||||
}
|
}
|
||||||
|
@ -2057,3 +2057,17 @@ func TestRemoteIPFail(t *testing.T) {
|
|||||||
assert.Nil(t, ip)
|
assert.Nil(t, ip)
|
||||||
assert.False(t, trust)
|
assert.False(t, trust)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestContextWithFallbackValueFromRequestContext(t *testing.T) {
|
||||||
|
var key struct{}
|
||||||
|
c := &Context{}
|
||||||
|
c.Request, _ = http.NewRequest("POST", "/", nil)
|
||||||
|
c.Request = c.Request.WithContext(context.WithValue(context.TODO(), key, "value"))
|
||||||
|
|
||||||
|
assert.Equal(t, "value", c.Value(key))
|
||||||
|
|
||||||
|
c2 := &Context{}
|
||||||
|
c2.Request, _ = http.NewRequest("POST", "/", nil)
|
||||||
|
c2.Request = c2.Request.WithContext(context.WithValue(context.TODO(), "key", "value2"))
|
||||||
|
assert.Equal(t, "value2", c2.Value("key"))
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user