89 lines
1.4 KiB
Go
89 lines
1.4 KiB
Go
package notifier
|
|
|
|
|
|
import (
|
|
"errors"
|
|
"sync"
|
|
)
|
|
|
|
type Sessions struct {
|
|
m sync.Map
|
|
}
|
|
|
|
func NewSessions() *Sessions {
|
|
cs := Sessions{
|
|
m: sync.Map{},
|
|
}
|
|
return &cs
|
|
}
|
|
|
|
func (c *Sessions) Get(id string) (*Session, error) {
|
|
v, ok := c.m.Load(id)
|
|
if !ok {
|
|
return nil, errors.New("not found")
|
|
}
|
|
if ret, ok := v.(*Session); ok {
|
|
return ret, nil
|
|
}
|
|
return nil, errors.New("value not a comsumer")
|
|
}
|
|
|
|
func (c *Sessions) Set(id string, session *Session) *Session {
|
|
v, ok := c.m.Swap(id, session)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
if ret, ok := v.(*Session); ok {
|
|
return ret
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *Sessions) Range(f func(string, *Session) bool) {
|
|
c.m.Range(func(k, v any) bool {
|
|
id, ok := k.(string)
|
|
if !ok {
|
|
return false
|
|
}
|
|
consumer, ok := v.(*Session)
|
|
if !ok {
|
|
return false
|
|
}
|
|
return f(id, consumer)
|
|
})
|
|
}
|
|
|
|
func (c *Sessions) List() []*Session {
|
|
ret := []*Session{}
|
|
c.m.Range(func(key, value any) bool {
|
|
consumer, ok := value.(*Session)
|
|
if !ok {
|
|
return false
|
|
}
|
|
ret = append(ret, consumer)
|
|
return true
|
|
})
|
|
return ret
|
|
}
|
|
|
|
func (c *Sessions) Map() map[string]*Session {
|
|
ret := make(map[string]*Session)
|
|
c.m.Range(func(key, value any) bool {
|
|
id, ok := key.(string)
|
|
if !ok {
|
|
return false
|
|
}
|
|
consumer, ok := value.(*Session)
|
|
if !ok {
|
|
return false
|
|
}
|
|
ret[id] = consumer
|
|
return true
|
|
})
|
|
return ret
|
|
}
|
|
|
|
func (c *Sessions) Delete(id string) {
|
|
c.m.Delete(id)
|
|
}
|