Skip to content

Commit 298ebca

Browse files
authored
fix missing initial sync.RWMutex (#2305)
* fix missing initial sync.RWMutex Signed-off-by: Bo-Yi Wu <[email protected]> * Add unit testing. Signed-off-by: Bo-Yi Wu <[email protected]>
1 parent 57f99ca commit 298ebca

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

context.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,10 @@ func (c *Context) Error(err error) *Error {
228228
// Set is used to store a new key/value pair exclusively for this context.
229229
// It also lazy initializes c.Keys if it was not used previously.
230230
func (c *Context) Set(key string, value interface{}) {
231+
if c.KeysMutex == nil {
232+
c.KeysMutex = &sync.RWMutex{}
233+
}
234+
231235
c.KeysMutex.Lock()
232236
if c.Keys == nil {
233237
c.Keys = make(map[string]interface{})
@@ -240,6 +244,10 @@ func (c *Context) Set(key string, value interface{}) {
240244
// Get returns the value for the given key, ie: (value, true).
241245
// If the value does not exists it returns (nil, false)
242246
func (c *Context) Get(key string) (value interface{}, exists bool) {
247+
if c.KeysMutex == nil {
248+
c.KeysMutex = &sync.RWMutex{}
249+
}
250+
243251
c.KeysMutex.RLock()
244252
value, exists = c.Keys[key]
245253
c.KeysMutex.RUnlock()

context_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1920,3 +1920,16 @@ func TestRaceParamsContextCopy(t *testing.T) {
19201920
performRequest(router, "GET", "/name2/api")
19211921
wg.Wait()
19221922
}
1923+
1924+
func TestContextWithKeysMutex(t *testing.T) {
1925+
c := &Context{}
1926+
c.Set("foo", "bar")
1927+
1928+
value, err := c.Get("foo")
1929+
assert.Equal(t, "bar", value)
1930+
assert.True(t, err)
1931+
1932+
value, err = c.Get("foo2")
1933+
assert.Nil(t, value)
1934+
assert.False(t, err)
1935+
}

go.sum

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
23
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
34
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
45
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=

0 commit comments

Comments
 (0)