diff --git a/cache.go b/cache.go index 30b1ea2..99135fc 100644 --- a/cache.go +++ b/cache.go @@ -135,6 +135,25 @@ func (c *cache) Get(k string) (interface{}, bool) { return item.Object, true } +// Get full Item from cache (with info about expiration). +// Returns full Item, when allowExpired is set to true returning item even if already expired and a bool indicating +// whether the key was found. +func (c *cache) GetItem(k string, allowExpired bool) (Item, bool) { + c.mu.RLock() + defer c.mu.RUnlock() + + item, found := c.items[k] + if !found { + return Item{}, false + } + + if !allowExpired && item.Expired() { + return Item{}, false + } + + return item, true +} + // GetWithExpiration returns an item and its expiration time from the cache. // It returns the item or nil, the expiration time if one is set (if the item // never expires a zero value for time.Time is returned), and a bool indicating diff --git a/cache_test.go b/cache_test.go index 47a3d53..ed0c099 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1413,6 +1413,38 @@ func TestFileSerialization(t *testing.T) { } } +func TestGetItem(t *testing.T) { + tc := New(DefaultExpiration, 0) + tc.Set("int8", int8(5), 25*time.Microsecond) + n, err := tc.DecrementInt8("int8", 2) + if err != nil { + t.Error("Error decrementing:", err) + } + if n != 3 { + t.Error("Returned number is not 3:", n) + } + time.Sleep(50 * time.Microsecond) + + x, found := tc.Get("int8") + if found { + t.Error("int8 should be expired") + } + + _, found = tc.GetItem("int8", false) + if found { + t.Error("int8 should be expired") + } + + item, found := tc.GetItem("int8", true) + if !found { + t.Error("int8 stale was not found") + } + + if item.Object.(int8) != 3 { + t.Error("int8 is not 3:", x) + } +} + func TestSerializeUnserializable(t *testing.T) { tc := New(DefaultExpiration, 0) ch := make(chan bool, 1)