From 63ea70e00b36743531e57a8be535730d5513c9ca Mon Sep 17 00:00:00 2001 From: vitams Date: Wed, 10 Apr 2019 23:50:35 +0500 Subject: [PATCH] Add method for delete by regex rule --- cache.go | 11 +++++++++++ cache_test.go | 13 +++++++++++++ 2 files changed, 24 insertions(+) diff --git a/cache.go b/cache.go index db88d2f..f602d5e 100644 --- a/cache.go +++ b/cache.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "os" + "regexp" "runtime" "sync" "time" @@ -911,6 +912,16 @@ func (c *cache) Delete(k string) { } } +// Delete an item from the cache by regex rule +func (c *cache) DeleteRegex(rule string) { + re, _ := regexp.Compile(rule) + for k := range c.items { + if re.MatchString(k) { + c.Delete(k) + } + } +} + func (c *cache) delete(k string) (interface{}, bool) { if c.onEvicted != nil { if v, found := c.items[k]; found { diff --git a/cache_test.go b/cache_test.go index cb80b38..5bf1930 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1150,6 +1150,19 @@ func TestDelete(t *testing.T) { } } +func TestDeleteRegex(t *testing.T) { + tc := New(DefaultExpiration, 0) + tc.Set("foo1", "bar", DefaultExpiration) + tc.DeleteRegex(`^foo`) + x, found := tc.Get("foo") + if found { + t.Error("foo was found, but it should have been deleted") + } + if x != nil { + t.Error("x is not nil:", x) + } +} + func TestItemCount(t *testing.T) { tc := New(DefaultExpiration, 0) tc.Set("foo", "1", DefaultExpiration)