Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mutex for protect Context.Keys map #1391

Merged
merged 7 commits into from
Mar 16, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add mutex for protect Context.Keys map
  • Loading branch information
mykolaCodes committed Jun 12, 2018
commit 6b246c7fe000cd7328ec3fad2503efaeab3b5b1b
10 changes: 10 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"net/url"
"os"
"strings"
"sync"
"time"

"github.com/gin-contrib/sse"
Expand Down Expand Up @@ -49,6 +50,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 @@ -68,6 +72,7 @@ func (c *Context) reset() {
c.Params = c.Params[0:0]
c.handlers = nil
c.index = -1
c.KeysMutex = &sync.RWMutex{}
c.Keys = nil
c.Errors = c.Errors[0:0]
c.Accepted = nil
Expand Down Expand Up @@ -180,16 +185,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