statping/handlers/cache.go

99 lines
1.8 KiB
Go
Raw Normal View History

2018-10-21 19:36:11 +00:00
package handlers
import (
"github.com/hunterlong/statping/utils"
2018-10-21 19:36:11 +00:00
"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
2020-02-04 06:37:32 +00:00
Lock()
Unlock()
2018-10-21 19:36:11 +00:00
}
// Item is a cached reference
type Item struct {
Content []byte
Expiration int64
}
2020-02-04 06:37:32 +00:00
// CleanRoutine is a go routine to automatically remove expired caches that haven't been hit recently
func CleanRoutine() {
for CacheStorage != nil {
CacheStorage.Lock()
for k, v := range CacheStorage.List() {
if v.Expired() {
CacheStorage.Delete(k)
}
}
CacheStorage.Unlock()
time.Sleep(5 * time.Second)
}
}
2018-10-21 19:36:11 +00:00
// Expired returns true if the item has expired.
func (item Item) Expired() bool {
if item.Expiration == 0 {
return false
}
return utils.Now().UnixNano() > item.Expiration
2018-10-21 19:36:11 +00:00
}
//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{},
}
}
2020-02-04 06:37:32 +00:00
func (s Storage) Lock() {
s.mu.Lock()
}
func (s Storage) Unlock() {
s.mu.Unlock()
}
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: utils.Now().Add(duration).UnixNano(),
2018-10-21 19:36:11 +00:00
}
}