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.
nnet/session/session.go

105 lines
1.7 KiB
Go

package session
import (
"sync"
)
type Session struct {
sync.RWMutex // 数据锁
id int64 // Session全局唯一ID
uid string // 用户ID不绑定的情况下与sid一致
data map[string]any // session数据存储内存
}
func NewSession(id int64) *Session {
return &Session{
id: id,
uid: "",
data: make(map[string]any),
}
}
// ID 获取 session ID
func (s *Session) ID() int64 {
return s.id
}
// UID 获取UID
func (s *Session) UID() string {
return s.uid
}
// Bind 绑定uid
func (s *Session) Bind(uid string) {
s.uid = uid
}
// 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.uid = ""
s.data = make(map[string]any)
}
// Close 关闭
func (s *Session) Close() {
s.Invalidate()
}