diff --git a/README.md b/README.md index c5789cc..2438397 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,13 @@ func main() { // ... // foo can then be passed around freely as a string + // Want to get the entry in the cache for an item not just the value? + var cahceItem Item + if x, found := c.GetCacheItem("foo"); found { + foo = x.(string) + } + // .. + // Want performance? Store pointers! c.Set("foo", &MyStruct, cache.DefaultExpiration) if x, found := c.Get("foo"); found { diff --git a/cache.go b/cache.go index 30b1ea2..109cef5 100644 --- a/cache.go +++ b/cache.go @@ -115,7 +115,22 @@ func (c *cache) Replace(k string, x interface{}, d time.Duration) error { return nil } -// Get an item from the cache. Returns the item or nil, and a bool indicating +// Get an item from the cache, along with its expiration time. +// Returns the item or nil, and a bool indicating whether the key was found. +func (c *cache) GetCacheItem(k string) (Item, bool) { + c.mu.RLock() + // "Inlining" of get and Expired + item, found := c.items[k] + if !found { + c.mu.RUnlock() + return Item{}, false + } + + c.mu.RUnlock() + return item, true +} + +// Get the value of an item from the cache. Returns the value or nil, and a bool indicating // whether the key was found. func (c *cache) Get(k string) (interface{}, bool) { c.mu.RLock() diff --git a/cache_test.go b/cache_test.go index 47a3d53..7228ee6 100644 --- a/cache_test.go +++ b/cache_test.go @@ -106,6 +106,28 @@ func TestCacheTimes(t *testing.T) { } } +func TestExpiredCacheRetrieval(t *testing.T) { + var found bool + + tc := New(50*time.Millisecond, 2*time.Second) + tc.Set("a", 1, DefaultExpiration) + + <-time.After(60 * time.Millisecond) + _, found = tc.Get("a") + if found { + t.Error("Found c when it should have been automatically deleted") + } + + item, found := tc.GetCacheItem("a") + if !found { + t.Error("Not Found an expired cache item a when it should have been in the cache") + } + + if !item.Expired() { + t.Error("Found cache item a marked as not expired when it should have been expired") + } +} + func TestNewFrom(t *testing.T) { m := map[string]Item{ "a": Item{