From 298ebca69107001096eaf81c4b4977b14ffa0e6d Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Fri, 27 Mar 2020 10:57:36 +0800 Subject: [PATCH] fix missing initial sync.RWMutex (#2305) * fix missing initial sync.RWMutex Signed-off-by: Bo-Yi Wu * Add unit testing. Signed-off-by: Bo-Yi Wu --- context.go | 8 ++++++++ context_test.go | 13 +++++++++++++ go.sum | 1 + 3 files changed, 22 insertions(+) diff --git a/context.go b/context.go index 5c1fab2..a2384c0 100644 --- a/context.go +++ b/context.go @@ -228,6 +228,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{}) @@ -240,6 +244,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() diff --git a/context_test.go b/context_test.go index 80c7b40..ce077bc 100644 --- a/context_test.go +++ b/context_test.go @@ -1920,3 +1920,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 d499815..4c14fb8 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=