Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
This commit is contained in:
Bo-Yi Wu 2020-05-03 19:06:45 +08:00
parent 76511522da
commit 6a7a41b634

View File

@ -53,13 +53,10 @@ type Context struct {
engine *Engine engine *Engine
EnablekeysMutex bool EnableMutexLock bool
// This mutex protect Keys map // This mutex protect Keys map
keysMutex *sync.RWMutex mu sync.RWMutex
// only initial keysMutex once
once sync.Once
// Keys is a key/value pair exclusively for the context of each request. // Keys is a key/value pair exclusively for the context of each request.
Keys map[string]interface{} Keys map[string]interface{}
@ -98,15 +95,17 @@ func (c *Context) reset() {
c.Accepted = nil c.Accepted = nil
c.queryCache = nil c.queryCache = nil
c.formCache = nil c.formCache = nil
if c.EnablekeysMutex {
c.keysMutex = &sync.RWMutex{}
}
} }
// Copy returns a copy of the current context that can be safely used outside the request's scope. // Copy returns a copy of the current context that can be safely used outside the request's scope.
// This has to be used when the context has to be passed to a goroutine. // This has to be used when the context has to be passed to a goroutine.
func (c *Context) Copy() *Context { func (c *Context) Copy() *Context {
var cp = *c cp := Context{
writermem: c.writermem,
Request: c.Request,
Params: c.Params,
engine: c.engine,
}
cp.writermem.ResponseWriter = nil cp.writermem.ResponseWriter = nil
cp.Writer = &cp.writermem cp.Writer = &cp.writermem
cp.index = abortIndex cp.index = abortIndex
@ -236,14 +235,9 @@ func (c *Context) Error(err error) *Error {
// Set is used to store a new key/value pair exclusively for this context. // 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. // It also lazy initializes c.Keys if it was not used previously.
func (c *Context) Set(key string, value interface{}) { func (c *Context) Set(key string, value interface{}) {
if c.EnablekeysMutex { if c.EnableMutexLock {
if c.keysMutex == nil { c.mu.Lock()
c.once.Do(func() { defer c.mu.Unlock()
c.keysMutex = &sync.RWMutex{}
})
}
c.keysMutex.Lock()
defer c.keysMutex.Unlock()
} }
if c.Keys == nil { if c.Keys == nil {
@ -256,14 +250,9 @@ func (c *Context) Set(key string, value interface{}) {
// Get returns the value for the given key, ie: (value, true). // Get returns the value for the given key, ie: (value, true).
// If the value does not exists it returns (nil, false) // If the value does not exists it returns (nil, false)
func (c *Context) Get(key string) (value interface{}, exists bool) { func (c *Context) Get(key string) (value interface{}, exists bool) {
if c.EnablekeysMutex { if c.EnableMutexLock {
if c.keysMutex == nil { c.mu.RLock()
c.once.Do(func() { defer c.mu.RUnlock()
c.keysMutex = &sync.RWMutex{}
})
}
c.keysMutex.RLock()
defer c.keysMutex.RUnlock()
} }
value, exists = c.Keys[key] value, exists = c.Keys[key]