diff --git a/cache.go b/cache.go index db88d2f..e1ccbc1 100644 --- a/cache.go +++ b/cache.go @@ -922,6 +922,21 @@ func (c *cache) delete(k string) (interface{}, bool) { return nil, false } +// Expire overrides the expiry tim of an existing item. If the duration is 0 +// (DefaultExpiration), the cache's default expiration time is used. If it is -1 +// (NoExpiration), the item never expires. +func (c *cache) Expire(k string, d time.Duration) error { + c.mu.Lock() + item, found := c.items[k] + if !found || (item.Expiration > 0 && time.Now().UnixNano() > item.Expiration) { + c.mu.Unlock() + return fmt.Errorf("Item %s doesn't exist", k) + } + c.set(k, item.Object, d) + c.mu.Unlock() + return nil +} + type keyAndValue struct { key string value interface{} diff --git a/cache_test.go b/cache_test.go index de3e9d6..539edc2 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1378,7 +1378,7 @@ func TestFileSerialization(t *testing.T) { tc := New(DefaultExpiration, 0) tc.Add("a", "a", DefaultExpiration) tc.Add("b", "b", DefaultExpiration) - f, err := ioutil.TempFile("", "go-cache-cache.dat") + f, err := ioutil.TempFile("", "go-cache-1-cache.dat") if err != nil { t.Fatal("Couldn't create cache file:", err) } @@ -1769,3 +1769,36 @@ func TestGetWithExpiration(t *testing.T) { t.Error("expiration for e is in the past") } } + +func TestExpire(t *testing.T) { + var ( + ct = time.Now() + tc = New(DefaultExpiration, 0) + ) + tc.Set("a", 1, time.Second) + if err := tc.Expire("a", time.Second); err != nil { + t.Error("expected err to be nil; value", err) + } + + _, expiration, found := tc.GetWithExpiration("a") + if !found { + t.Error("e was not found while getting e2") + } + if expiration.IsZero() { + t.Error("expected expiration not to be zero") + } + if d := expiration.Sub(ct); d <= time.Second { + t.Error("expected difference to be lesser than or equal to one second", d) + } + if err := tc.Expire("a", DefaultExpiration); err != nil { + t.Error("expected err to be nil; value", err) + } + + _, expiration, found = tc.GetWithExpiration("a") + if !found { + t.Error("e was not found while getting e2") + } + if !expiration.IsZero() { + t.Error("expected expiration to be zero") + } +}