diff --git a/cache2go/cache.go b/cache2go/cache.go index 9fde2248c..4aee5b2ef 100644 --- a/cache2go/cache.go +++ b/cache2go/cache.go @@ -11,6 +11,7 @@ import ( type expiringCacheEntry interface { XCache(key string, expire time.Duration, value expiringCacheEntry) timer() *time.Timer + age() time.Duration KeepAlive() } @@ -70,6 +71,11 @@ func (xe *XEntry) timer() *time.Timer { return xe.t } +func (xe *XEntry) age() time.Duration { + return time.Since(xe.timestamp) + +} + // Mark entry to be kept another expirationDuration period func (xe *XEntry) KeepAlive() { xe.Lock() @@ -105,6 +111,24 @@ func GetCached(key string) (v interface{}, err error) { return nil, errors.New("not found") } +func GetKeyAge(key string) (time.Duration, error) { + mux.RLock() + defer mux.RUnlock() + if r, ok := cache[key]; ok { + return time.Since(r.timestamp), nil + } + return 0, errors.New("not found") +} + +func GetXKeyAge(key string) (time.Duration, error) { + xMux.RLock() + defer xMux.RUnlock() + if r, ok := xcache[key]; ok { + return r.age(), nil + } + return 0, errors.New("not found") +} + func RemKey(key string) { mux.Lock() defer mux.Unlock() diff --git a/cache2go/cache_test.go b/cache2go/cache_test.go index 010e786a5..f7313dae1 100644 --- a/cache2go/cache_test.go +++ b/cache2go/cache_test.go @@ -96,3 +96,20 @@ func TestXRemKey(t *testing.T) { t.Error("Error removing xcached key: ", err, t1) } } + +func TestGetKeyAge(t *testing.T) { + Cache("t1", "test") + d, err := GetKeyAge("t1") + if err != nil || d > time.Millisecond || d < time.Nanosecond { + t.Error("Error getting cache key age: ", d) + } +} + +func TestXGetKeyAge(t *testing.T) { + a := &myStruct{data: "mama are mere"} + a.XCache("t1", 10*time.Second, a) + d, err := GetXKeyAge("t1") + if err != nil || d > time.Millisecond || d < time.Nanosecond { + t.Error("Error getting cache key age: ", d) + } +}