diff --git a/context.go b/context.go index 1a953006c0..9458423078 100644 --- a/context.go +++ b/context.go @@ -43,6 +43,9 @@ const BodyBytesKey = "_gin-gonic/gin/bodybyteskey" // abortIndex represents a typical value used in abort functions. const abortIndex int8 = math.MaxInt8 >> 1 +// &Ctx is the key that a Context returns itself for. +var Ctx int + // Context is the most important part of gin. It allows us to pass variables between middleware, // manage the flow, validate the JSON of a request and render a JSON response for example. type Context struct { @@ -1192,6 +1195,9 @@ func (c *Context) Value(key interface{}) interface{} { if key == 0 { return c.Request } + if key == &Ctx { + return c + } if keyAsString, ok := key.(string); ok { if val, exists := c.Get(keyAsString); exists { return val diff --git a/context_test.go b/context_test.go index ffbe5ccaa3..5ab106632d 100644 --- a/context_test.go +++ b/context_test.go @@ -1861,6 +1861,7 @@ func TestContextGolangContext(t *testing.T) { assert.Equal(t, ti, time.Time{}) assert.False(t, ok) assert.Equal(t, c.Value(0), c.Request) + assert.Equal(t, c.Value(&Ctx), c) assert.Nil(t, c.Value("foo")) c.Set("foo", "bar")