diff --git a/cache.go b/cache.go index 3562543..00db76d 100644 --- a/cache.go +++ b/cache.go @@ -129,6 +129,29 @@ func (c *cache) Get(k string) (interface{}, bool) { return item.Object, true } +// get the item from cache and then reset the expiration date, this means +// you will need a full lock instead of a rlock +func (c *cache) GetR(k string, d time.Duration) (interface{}, bool) { + var e int64 + if d > 0 { + e = time.Now().Add(d).UnixNano() + } + + c.mu.Lock() + + if item, found := c.get(k); found { + c.items[k] = Item{ + Object: item, + Expiration: e, + } + c.mu.Unlock() + return item, found + } + + c.mu.Unlock() + return nil, false +} + func (c *cache) get(k string) (interface{}, bool) { item, found := c.items[k] if !found { diff --git a/cache_test.go b/cache_test.go index 6e81693..17baeaa 100644 --- a/cache_test.go +++ b/cache_test.go @@ -76,6 +76,7 @@ func TestCacheTimes(t *testing.T) { tc.Set("b", 2, NoExpiration) tc.Set("c", 3, 20*time.Millisecond) tc.Set("d", 4, 70*time.Millisecond) + tc.Set("e", 5, 100*time.Millisecond) <-time.After(25 * time.Millisecond) _, found = tc.Get("c") @@ -104,6 +105,17 @@ func TestCacheTimes(t *testing.T) { if found { t.Error("Found d when it should have been automatically deleted (later than the default)") } + + _, found = tc.GetR("e", 50 * time.Millisecond) + if !found { + t.Error("Should have found e because enough time hasn't passed") + } + + <-time.After(35 * time.Millisecond) + _, found = tc.Get("e") + if !found { + t.Error("Should have still found e because it was reset") + } } func TestNewFrom(t *testing.T) {