Add method to retrieve CacheItem rather than the value of the item only

This commit is contained in:
Rahul Raheja 2017-05-05 20:29:15 -04:00
parent 7ac151875f
commit c364809b54
3 changed files with 45 additions and 1 deletions

View File

@ -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 {

View File

@ -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()

View File

@ -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{