File tree Expand file tree Collapse file tree 3 files changed +22
-0
lines changed Expand file tree Collapse file tree 3 files changed +22
-0
lines changed Original file line number Diff line number Diff 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.
230230func (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)
242246func (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 ()
Original file line number Diff line number Diff 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+ }
Original file line number Diff line number Diff line change 11github.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 =
23github.com/davecgh/go-spew v1.1.1 /go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38 =
34github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE =
45github.com/gin-contrib/sse v0.1.0 /go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI =
You can’t perform that action at this time.
0 commit comments