diff --git a/cache.go b/cache.go index db88d2f..5420e00 100644 --- a/cache.go +++ b/cache.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "os" + "regexp" "runtime" "sync" "time" @@ -15,7 +16,7 @@ type Item struct { Expiration int64 } -// Returns true if the item has expired. +// Expired Returns true if the item has expired. func (item Item) Expired() bool { if item.Expiration == 0 { return false @@ -24,9 +25,9 @@ func (item Item) Expired() bool { } const ( - // For use with functions that take an expiration time. + // NoExpiration For use with functions that take an expiration time. NoExpiration time.Duration = -1 - // For use with functions that take an expiration time. Equivalent to + // DefaultExpiration For use with functions that take an expiration time. Equivalent to // passing in the same expiration duration as was given to New() or // NewFrom() when the cache was created (e.g. 5 minutes.) DefaultExpiration time.Duration = 0 @@ -45,7 +46,7 @@ type cache struct { janitor *janitor } -// Add an item to the cache, replacing any existing item. If the duration is 0 +// Set Add an item to the cache, replacing any existing item. If the duration is 0 // (DefaultExpiration), the cache's default expiration time is used. If it is -1 // (NoExpiration), the item never expires. func (c *cache) Set(k string, x interface{}, d time.Duration) { @@ -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 de3e9d6..1a4f9ed 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) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..8ba8c9d --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/vmpartner/go-cache + +go 1.16