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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 cacheItem Item
if x, found := c.GetCacheItem("foo"); found {
cacheItem = x.(string)
}
// ..

// Want performance? Store pointers!
c.Set("foo", &MyStruct, cache.DefaultExpiration)
if x, found := c.Get("foo"); found {
Expand Down
17 changes: 16 additions & 1 deletion cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
22 changes: 22 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down