statping/handlers/cache.go

74 lines
1.3 KiB
Go
Raw Normal View History

2018-10-21 19:36:11 +00:00
package handlers
import (
"sync"
"time"
)
2018-11-05 22:04:06 +00:00
var CacheStorage Cacher
2018-10-21 19:36:11 +00:00
type Cacher interface {
Get(key string) []byte
2018-11-05 22:04:06 +00:00
Delete(key string)
2018-10-21 19:36:11 +00:00
Set(key string, content []byte, duration time.Duration)
List() map[string]Item
2018-10-21 19:36:11 +00:00
}
// Item is a cached reference
type Item struct {
Content []byte
Expiration int64
}
// Expired returns true if the item has expired.
func (item Item) Expired() bool {
if item.Expiration == 0 {
return false
}
return time.Now().UnixNano() > item.Expiration
}
//Storage mecanism for caching strings in memory
type Storage struct {
items map[string]Item
mu *sync.RWMutex
}
2018-11-05 22:04:06 +00:00
//NewStorage creates a new in memory CacheStorage
2018-10-21 19:36:11 +00:00
func NewStorage() *Storage {
return &Storage{
items: make(map[string]Item),
mu: &sync.RWMutex{},
}
}
func (s Storage) List() map[string]Item {
return s.items
}
2018-10-21 19:36:11 +00:00
//Get a cached content by key
func (s Storage) Get(key string) []byte {
item := s.items[key]
if item.Expired() {
CacheStorage.Delete(key)
2018-10-21 19:36:11 +00:00
return nil
}
return item.Content
}
2018-11-05 22:04:06 +00:00
func (s Storage) Delete(key string) {
s.mu.Lock()
defer s.mu.Unlock()
2018-11-05 22:04:06 +00:00
delete(s.items, key)
}
2018-10-21 19:36:11 +00:00
//Set a cached content by key
func (s Storage) Set(key string, content []byte, duration time.Duration) {
s.mu.Lock()
defer s.mu.Unlock()
s.items[key] = Item{
Content: content,
Expiration: time.Now().Add(duration).UnixNano(),
}
}