used response cache in responder

This commit is contained in:
Radu Ioan Fericean
2015-07-20 12:15:24 +03:00
parent 835f6533da
commit a7cf099c5c
3 changed files with 51 additions and 7 deletions

View File

@@ -8,20 +8,25 @@ import (
var ErrNotFound = errors.New("NOT_FOUND")
type CacheItem struct {
Value interface{}
Err error
}
type ResponseCache struct {
ttl time.Duration
cache map[string]interface{}
cache map[string]*CacheItem
mu sync.RWMutex
}
func NewResponseCache(ttl time.Duration) *ResponseCache {
return &ResponseCache{
ttl: ttl,
cache: make(map[string]interface{}),
cache: make(map[string]*CacheItem),
}
}
func (rc *ResponseCache) Cache(key string, item interface{}) {
func (rc *ResponseCache) Cache(key string, item *CacheItem) {
rc.mu.Lock()
rc.cache[key] = item
rc.mu.Unlock()
@@ -33,7 +38,7 @@ func (rc *ResponseCache) Cache(key string, item interface{}) {
}()
}
func (rc *ResponseCache) Get(key string) (interface{}, error) {
func (rc *ResponseCache) Get(key string) (*CacheItem, error) {
rc.mu.RLock()
defer rc.mu.RUnlock()
item, ok := rc.cache[key]

View File

@@ -7,16 +7,16 @@ import (
func TestRCacheSetGet(t *testing.T) {
rc := NewResponseCache(5 * time.Second)
rc.Cache("test", "best")
rc.Cache("test", &CacheItem{Value: "best"})
v, err := rc.Get("test")
if err != nil || v.(string) != "best" {
if err != nil || v.Value.(string) != "best" {
t.Error("Error retriving response cache: ", v, err)
}
}
func TestRCacheExpire(t *testing.T) {
rc := NewResponseCache(1 * time.Microsecond)
rc.Cache("test", "best")
rc.Cache("test", &CacheItem{Value: "best"})
time.Sleep(1 * time.Millisecond)
_, err := rc.Get("test")
if err == nil {