Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,34 @@ func (c *cache) delete(k string) {
delete(c.items, k)
}

func (c *cache) Expire(k string, d time.Duration) error {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid code duplication I suggest to replace the method implementation with the following code:

func (c *cache) Expire(k string, d time.Duration) error {
	e := time.Now().Add(d)
	return c.ExpireAt(k, e)
}

Also, I would rename this method to 'ExpireAfter'.

c.Lock()
v, found := c.items[k]
if !found || v.Expired() {
c.Unlock()
return fmt.Errorf("key %s not found.", k)
}

e := time.Now().Add(d)
v.Expiration = &e

c.Unlock()
return nil
}

func (c *cache) ExpireAt(k string, expire *time.Time) error {
c.Lock()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The defer c.Unlock() should be used here to automatically release the resource.

v, found := c.items[k]
if !found || v.Expired() {
c.Unlock()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should be removed if the defer c.Unlock() is used.

return fmt.Errorf("key %s not found.", k)
}

v.Expiration = expire
c.Unlock()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should be removed if the defer c.Unlock() is used.

return nil
}

// Delete all expired items from the cache.
func (c *cache) DeleteExpired() {
c.Lock()
Expand Down