-
-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* feat: support multi pics * Update memogram.go --------- Co-authored-by: boojack <[email protected]>
- Loading branch information
1 parent
22e786f
commit cc43190
Showing
2 changed files
with
112 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package memogram | ||
|
||
import ( | ||
"sync" | ||
"time" | ||
) | ||
|
||
// Cache is a simple cache implementation | ||
type Cache struct { | ||
sync.RWMutex | ||
items map[string]*CacheItem | ||
} | ||
|
||
type CacheItem struct { | ||
Value interface{} | ||
Expiration time.Time | ||
} | ||
|
||
func NewCache() *Cache { | ||
return &Cache{ | ||
items: make(map[string]*CacheItem), | ||
} | ||
} | ||
|
||
// set adds a key value pair to the cache with a given duration | ||
func (c *Cache) set(key string, value interface{}, duration time.Duration) { | ||
c.Lock() | ||
defer c.Unlock() | ||
c.items[key] = &CacheItem{ | ||
Value: value, | ||
Expiration: time.Now().Add(duration), | ||
} | ||
} | ||
|
||
// get returns a value from the cache if it exists | ||
func (c *Cache) get(key string) (interface{}, bool) { | ||
c.RLock() | ||
defer c.RUnlock() | ||
item, found := c.items[key] | ||
if !found { | ||
return nil, false | ||
} | ||
if time.Now().After(item.Expiration) { | ||
return nil, false | ||
} | ||
return item.Value, true | ||
} | ||
|
||
// deleteExpired deletes all expired key value pairs | ||
func (c *Cache) deleteExpired() { | ||
c.Lock() | ||
defer c.Unlock() | ||
for k, v := range c.items { | ||
if time.Now().After(v.Expiration) { | ||
delete(c.items, k) | ||
} | ||
} | ||
} | ||
|
||
// startGC starts a goroutine to clean expired key value pairs | ||
func (c *Cache) startGC() { | ||
go func() { | ||
for { | ||
<-time.After(5 * time.Minute) | ||
c.deleteExpired() | ||
} | ||
}() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters