You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
94 lines
1.4 KiB
Go
94 lines
1.4 KiB
Go
package ncmd
|
|
|
|
import "sync"
|
|
|
|
type Session struct {
|
|
id int64 // 唯一ID
|
|
data map[string]any // 数据存储
|
|
|
|
*sync.RWMutex
|
|
}
|
|
|
|
func NewSession(id int64) *Session {
|
|
return &Session{
|
|
id: id,
|
|
data: make(map[string]any),
|
|
RWMutex: &sync.RWMutex{},
|
|
}
|
|
}
|
|
|
|
func (s *Session) Id() int64 {
|
|
return s.id
|
|
}
|
|
|
|
func (s *Session) SetId(id int64) {
|
|
s.id = id
|
|
}
|
|
|
|
// Attribute 获取指定key对应参数
|
|
func (s *Session) Attribute(key string) any {
|
|
s.RLock()
|
|
defer s.RUnlock()
|
|
|
|
return s.data[key]
|
|
}
|
|
|
|
// Keys 获取所有参数key
|
|
func (s *Session) Keys() []string {
|
|
s.RLock()
|
|
defer s.RUnlock()
|
|
|
|
keys := make([]string, 0, len(s.data))
|
|
for k := range s.data {
|
|
keys = append(keys, k)
|
|
}
|
|
return keys
|
|
}
|
|
|
|
// Exists 指定key是否存在
|
|
func (s *Session) Exists(key string) bool {
|
|
s.RLock()
|
|
defer s.RUnlock()
|
|
|
|
_, has := s.data[key]
|
|
return has
|
|
}
|
|
|
|
// Attributes 获取所有参数
|
|
func (s *Session) Attributes() map[string]any {
|
|
s.RLock()
|
|
defer s.RUnlock()
|
|
|
|
return s.data
|
|
}
|
|
|
|
// RemoveAttribute 移除指定key对应参数
|
|
func (s *Session) RemoveAttribute(key string) {
|
|
s.Lock()
|
|
defer s.Unlock()
|
|
|
|
delete(s.data, key)
|
|
}
|
|
|
|
// SetAttribute 设置参数
|
|
func (s *Session) SetAttribute(key string, value any) {
|
|
s.Lock()
|
|
defer s.Unlock()
|
|
|
|
s.data[key] = value
|
|
}
|
|
|
|
// Invalidate 清理
|
|
func (s *Session) Invalidate() {
|
|
s.Lock()
|
|
defer s.Unlock()
|
|
|
|
s.id = 0
|
|
s.data = make(map[string]any)
|
|
}
|
|
|
|
// Close 关闭
|
|
func (s *Session) Close() {
|
|
s.Invalidate()
|
|
}
|