Skip to content

Commit

Permalink
feat(context): return GIN Context from Value method
Browse files Browse the repository at this point in the history
  • Loading branch information
ifaisalalam committed Aug 14, 2021
1 parent b463b1c commit 7220d2a
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
6 changes: 6 additions & 0 deletions context.go
Expand Up @@ -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

// &CtxKey is the key that a Context returns itself for.
var CtxKey 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 {
Expand Down Expand Up @@ -1192,6 +1195,9 @@ func (c *Context) Value(key interface{}) interface{} {
if key == 0 {
return c.Request
}
if key == &CtxKey {
return c
}
if keyAsString, ok := key.(string); ok {
if val, exists := c.Get(keyAsString); exists {
return val
Expand Down
1 change: 1 addition & 0 deletions context_test.go
Expand Up @@ -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(&CtxKey), c)
assert.Nil(t, c.Value("foo"))

c.Set("foo", "bar")
Expand Down

0 comments on commit 7220d2a

Please sign in to comment.