From 9fd1cc3d2b3f983949a123a401cedf951e3335d5 Mon Sep 17 00:00:00 2001 From: master quo que qua Date: Sat, 2 Jan 2021 13:04:13 +0800 Subject: [PATCH] added context-value support --- context.go | 15 +++++++++++++++ context_test.go | 19 +++++++++++++++++++ go.sum | 1 + 3 files changed, 35 insertions(+) diff --git a/context.go b/context.go index 3d6b56d6..eb6c81b4 100644 --- a/context.go +++ b/context.go @@ -1128,3 +1128,18 @@ func (c *Context) Value(key interface{}) interface{} { } return nil } + +// ContextValue returns the context's value associated with the http request based on key, or nil +// if no value is associated. +func (c *Context) ContextValue(key interface{}) interface{} { + if key == 0 { + // to make sure the api(s) are consistent in behaviour; return the Request object instead of a nil. + // check the [Value] method's implementation (context.go). + return c.Request + } + if keyAsString, ok := key.(string); ok { + val := c.Request.Context().Value(keyAsString) + return val + } + return nil +} diff --git a/context_test.go b/context_test.go index 8e1e3b57..f0315b4a 100644 --- a/context_test.go +++ b/context_test.go @@ -1960,3 +1960,22 @@ func TestContextWithKeysMutex(t *testing.T) { assert.Nil(t, value) assert.False(t, err) } + +func TestContextValueRequest(t *testing.T) { + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + + c.Request, _ = http.NewRequest("GET", "/", nil) + + // set the context value(s) + c1 := c.Request.Context() + c1 = context.WithValue(c1, interface{}("foo"), "bar") + c1 = context.WithValue(c1, interface{}("foo2"), "BAR2") + + // set the context back to the request + c.Request = c.Request.WithContext(c1) + + // testing + assert.Equal(t, "bar", c.ContextValue("foo")) + assert.Equal(t, "BAR2", c.ContextValue("foo2")) +} diff --git a/go.sum b/go.sum index a64b3319..403dd8f2 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,7 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLD github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=