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.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package session
import (
"sync"
)
type Session struct {
sync . RWMutex // 数据锁
id int64 // Session全局唯一ID
uid string // 用户ID, 不绑定的情况下与sid一致
data map [ string ] interface { } // session数据存储( 内存)
}
func NewSession ( id int64 ) * Session {
return & Session {
id : id ,
uid : "" ,
data : make ( map [ string ] interface { } ) ,
}
}
// 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 ) interface { } {
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 ] interface { } {
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 interface { } ) {
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 ] interface { } )
}
// Close 关闭
func ( s * Session ) Close ( ) {
s . Invalidate ( )
}