initial
This commit is contained in:
parent
46f4078530
commit
89211faa49
15
cache.go
15
cache.go
|
@ -135,6 +135,21 @@ func (c *cache) Get(k string) (interface{}, bool) {
|
||||||
return item.Object, true
|
return item.Object, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOrSet an item from the cache or sets default if not found. Returns the
|
||||||
|
// existing item or v if none was found, and a bool indicating
|
||||||
|
// whether the key was found.
|
||||||
|
func (c *cache) GetOrSet(k string, v interface{}, d time.Duration) (interface{}, bool) {
|
||||||
|
c.mu.Lock()
|
||||||
|
item, found := c.get(k)
|
||||||
|
if !found {
|
||||||
|
c.set(k, v, d)
|
||||||
|
c.mu.Unlock()
|
||||||
|
return v, false
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
return item, true
|
||||||
|
}
|
||||||
|
|
||||||
// GetWithExpiration returns an item and its expiration time from the cache.
|
// 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
|
// 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
|
// never expires a zero value for time.Time is returned), and a bool indicating
|
||||||
|
|
|
@ -68,6 +68,20 @@ func TestCache(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetOrSet(t *testing.T) {
|
||||||
|
tc := New(DefaultExpiration, 0)
|
||||||
|
|
||||||
|
a, found := tc.GetOrSet("a", "v", DefaultExpiration)
|
||||||
|
if found || a.(string) != "v" {
|
||||||
|
t.Error("Getting a not found value not equal to default", a)
|
||||||
|
}
|
||||||
|
|
||||||
|
a, found = tc.GetOrSet("a", "v2", DefaultExpiration)
|
||||||
|
if !found || a.(string) != "v" {
|
||||||
|
t.Error("Getting a found value not equal to original", a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCacheTimes(t *testing.T) {
|
func TestCacheTimes(t *testing.T) {
|
||||||
var found bool
|
var found bool
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue