Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down
35 changes: 34 additions & 1 deletion cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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")
}
}