From ba621af762a700554a6596829ba4f659b2696000 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Fri, 27 Mar 2020 09:13:48 +0800 Subject: [PATCH 1/2] fix missing initial sync.RWMutex Signed-off-by: Bo-Yi Wu --- context.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/context.go b/context.go index 572dbb81bb..dd4a2151c0 100644 --- a/context.go +++ b/context.go @@ -224,6 +224,10 @@ func (c *Context) Error(err error) *Error { // Set is used to store a new key/value pair exclusively for this context. // It also lazy initializes c.Keys if it was not used previously. func (c *Context) Set(key string, value interface{}) { + if c.KeysMutex == nil { + c.KeysMutex = &sync.RWMutex{} + } + c.KeysMutex.Lock() if c.Keys == nil { c.Keys = make(map[string]interface{}) @@ -236,6 +240,10 @@ func (c *Context) Set(key string, value interface{}) { // Get returns the value for the given key, ie: (value, true). // If the value does not exists it returns (nil, false) func (c *Context) Get(key string) (value interface{}, exists bool) { + if c.KeysMutex == nil { + c.KeysMutex = &sync.RWMutex{} + } + c.KeysMutex.RLock() value, exists = c.Keys[key] c.KeysMutex.RUnlock() From fdebef2da90eaa53ef921a2ccbc81716c85203b0 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Fri, 27 Mar 2020 10:07:36 +0800 Subject: [PATCH 2/2] Add unit testing. Signed-off-by: Bo-Yi Wu --- context_test.go | 13 +++++++++++++ go.sum | 1 + 2 files changed, 14 insertions(+) diff --git a/context_test.go b/context_test.go index 78b22c0d42..3e6a4781e7 100644 --- a/context_test.go +++ b/context_test.go @@ -1918,3 +1918,16 @@ func TestRaceParamsContextCopy(t *testing.T) { performRequest(router, "GET", "/name2/api") wg.Wait() } + +func TestContextWithKeysMutex(t *testing.T) { + c := &Context{} + c.Set("foo", "bar") + + value, err := c.Get("foo") + assert.Equal(t, "bar", value) + assert.True(t, err) + + value, err = c.Get("foo2") + assert.Nil(t, value) + assert.False(t, err) +} diff --git a/go.sum b/go.sum index d499815524..4c14fb83f7 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,5 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=