This commit is contained in:
Musin Vitaly 2021-06-08 00:50:54 +08:00 committed by GitHub
commit bee988153b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 4 deletions

View File

@ -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 {

View File

@ -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)

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module github.com/vmpartner/go-cache
go 1.16