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

context add RWMutex for key set and get Goroutine safe #2046

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
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
8 changes: 8 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"net/url"
"os"
"strings"
"sync"
"time"

"github.com/gin-contrib/sse"
Expand Down Expand Up @@ -55,6 +56,9 @@ type Context struct {
// Keys is a key/value pair exclusively for the context of each request.
Keys map[string]interface{}

// RWMutex for Keys Set and Get Goroutine safe
m sync.RWMutex

// Errors is a list of errors attached to all the handlers/middlewares who used this context.
Errors errorMsgs

Expand Down Expand Up @@ -219,6 +223,8 @@ 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.m.Lock()
defer c.m.Unlock()
if c.Keys == nil {
c.Keys = make(map[string]interface{})
}
Expand All @@ -228,6 +234,8 @@ 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) {
c.m.RLock()
defer c.m.RUnlock()
value, exists = c.Keys[key]
return
}
Expand Down