Skip to content

Commit

Permalink
Add mutex for protect Context.Keys map (gin-gonic#1391)
Browse files Browse the repository at this point in the history
* Add mutex for protect Context.Keys map

* Fix tests

Co-authored-by: Nikolay Tolkachov <nik.tolkachov@gmail.com>
Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
  • Loading branch information
3 people authored and byebyebruce committed Mar 25, 2020
1 parent 2183bc6 commit 7caa32d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
10 changes: 10 additions & 0 deletions context.go
Expand Up @@ -16,6 +16,7 @@ import (
"net/url"
"os"
"strings"
"sync"
"time"

"github.com/gin-contrib/sse"
Expand Down Expand Up @@ -52,6 +53,9 @@ type Context struct {

engine *Engine

// This mutex protect Keys map
KeysMutex *sync.RWMutex

// Keys is a key/value pair exclusively for the context of each request.
Keys map[string]interface{}

Expand All @@ -78,6 +82,7 @@ func (c *Context) reset() {
c.Params = c.Params[0:0]
c.handlers = nil
c.index = -1
c.KeysMutex = &sync.RWMutex{}
c.fullPath = ""
c.Keys = nil
c.Errors = c.Errors[0:0]
Expand Down Expand Up @@ -219,16 +224,21 @@ 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{}) {
c.KeysMutex.Lock()
if c.Keys == nil {
c.Keys = make(map[string]interface{})
}

c.Keys[key] = value
c.KeysMutex.Unlock()
}

// 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) {
c.KeysMutex.RLock()
value, exists = c.Keys[key]
c.KeysMutex.RUnlock()
return
}

Expand Down
2 changes: 1 addition & 1 deletion gin.go
Expand Up @@ -162,7 +162,7 @@ func Default() *Engine {
}

func (engine *Engine) allocateContext() *Context {
return &Context{engine: engine}
return &Context{engine: engine, KeysMutex: &sync.RWMutex{}}
}

// Delims sets template left and right delims and returns a Engine instance.
Expand Down

0 comments on commit 7caa32d

Please sign in to comment.