gin.Context with fallback value from c.Request.Context()

This commit is contained in:
wei840222 2021-06-15 22:24:34 +08:00 committed by wei.wan
parent f73c3f3795
commit ea979c8663
2 changed files with 21 additions and 3 deletions

View File

@ -1186,8 +1186,12 @@ func (c *Context) Value(key interface{}) interface{} {
return c.Request
}
if keyAsString, ok := key.(string); ok {
val, _ := c.Get(keyAsString)
return val
if val, exists := c.Get(keyAsString); exists {
return val
}
}
return nil
if c.Request == nil || c.Request.Context() == nil {
return nil
}
return c.Request.Context().Value(key)
}

View File

@ -2057,3 +2057,17 @@ func TestRemoteIPFail(t *testing.T) {
assert.Nil(t, ip)
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"))
}