util/context/context.go

98 lines
1.6 KiB
Go
Raw Normal View History

2017-11-10 07:05:28 +00:00
package context
2017-11-27 10:51:03 +00:00
import "sync"
2017-11-10 07:05:28 +00:00
type ContextKey string
func (c ContextKey) String() string {
return string(c)
}
2017-11-27 10:51:03 +00:00
func NewContext(parent Context) Context {
c := &defaultContext{
parent: parent,
}
c.attributes = make(map[string]interface{})
return c
}
type Context interface {
SetAttribute(key string, value interface{})
GetAttribute(key string) (value interface{})
RemoveAttribute(key string)
ContainsAttribute(key string) (exist bool)
}
type defaultContext struct {
parent Context
attributes map[string]interface{}
mtx sync.RWMutex
}
func (dc *defaultContext) SetAttribute(key string, value interface{}) {
dc.checkInitialized()
dc.mtx.Lock()
defer dc.mtx.Unlock()
dc.attributes[key] = value
}
func (dc *defaultContext) GetAttribute(key string) (value interface{}) {
dc.checkInitialized()
dc.mtx.RLock()
defer dc.mtx.RUnlock()
if _, ok := dc.attributes[key]; ok {
return dc.attributes[key]
}
if nil == dc.parent {
return nil
}
return dc.parent.GetAttribute(key)
}
func (dc *defaultContext) RemoveAttribute(key string) {
dc.checkInitialized()
dc.mtx.Lock()
defer dc.mtx.Unlock()
if _, ok := dc.attributes[key]; ok {
delete(dc.attributes, key)
return
}
if nil == dc.parent {
return
}
dc.parent.RemoveAttribute(key)
}
func (dc *defaultContext) ContainsAttribute(key string) (exist bool) {
dc.checkInitialized()
dc.mtx.RLock()
defer dc.mtx.RUnlock()
if _, ok := dc.attributes[key]; ok {
return true
}
if nil == dc.parent {
return false
}
return dc.parent.ContainsAttribute(key)
}
func (dc *defaultContext) checkInitialized() {
if nil == dc.attributes {
panic("Attribute Manager: must be initialized")
}
}