Skip to content

Commit

Permalink
fix missing initial sync.RWMutex (#2305)
Browse files Browse the repository at this point in the history
* fix missing initial sync.RWMutex

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>

* Add unit testing.

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
  • Loading branch information
appleboy committed Mar 27, 2020
1 parent 57f99ca commit 298ebca
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions context.go
Expand Up @@ -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{})
Expand All @@ -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()
Expand Down
13 changes: 13 additions & 0 deletions context_test.go
Expand Up @@ -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)
}
1 change: 1 addition & 0 deletions 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=
Expand Down

0 comments on commit 298ebca

Please sign in to comment.