You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
795 B
48 lines
795 B
package token |
|
|
|
import ( |
|
"sync" |
|
"time" |
|
) |
|
|
|
type ( |
|
Store interface { |
|
Set(key string, val any, duration time.Duration) error |
|
Get(key string) (any, bool) |
|
} |
|
node struct { |
|
data any |
|
expired time.Time |
|
} |
|
defaultStore struct { |
|
idMap map[string]*node |
|
lock sync.RWMutex |
|
} |
|
) |
|
|
|
func (d *defaultStore) Get(key string) (any, bool) { |
|
d.lock.RLock() |
|
defer d.lock.RUnlock() |
|
if v, ok := d.idMap[key]; ok { |
|
if time.Now().After(v.expired) { |
|
return v.data, true |
|
} |
|
} |
|
return nil, false |
|
} |
|
|
|
func (d *defaultStore) Set(key string, val any, duration time.Duration) error { |
|
d.lock.Lock() |
|
defer d.lock.Unlock() |
|
d.idMap[key] = &node{ |
|
data: val, |
|
expired: time.Now().Add(duration), |
|
} |
|
return nil |
|
} |
|
|
|
func newStore() Store { |
|
return &defaultStore{ |
|
idMap: make(map[string]*node), |
|
} |
|
}
|
|
|