summaryrefslogtreecommitdiff
path: root/src/cache
diff options
context:
space:
mode:
authorBrian Picciano <mediocregopher@gmail.com>2023-01-23 22:30:30 +0100
committerBrian Picciano <mediocregopher@gmail.com>2023-01-23 22:31:19 +0100
commitc1c1bb2c4c1baf37dbcce96f144966d4ada65ac5 (patch)
treec69d7bf531734f6435c2e3e8edd2e3ae50c2f5e8 /src/cache
parent024f51488614919240a71cae1cae1c8fe6df1229 (diff)
Implement cache and logger middlewares for gemini
Diffstat (limited to 'src/cache')
-rw-r--r--src/cache/cache.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/cache/cache.go b/src/cache/cache.go
new file mode 100644
index 0000000..ade286a
--- /dev/null
+++ b/src/cache/cache.go
@@ -0,0 +1,49 @@
+// Package cache implements a simple LRU cache which can be completely purged
+// whenever needed.
+package cache
+
+import (
+ lru "github.com/hashicorp/golang-lru"
+)
+
+// Cache describes an in-memory cache for arbitrary objects, which has a Purge
+// method for clearing everything at once.
+type Cache interface {
+ Get(key string) interface{}
+ Set(key string, value interface{})
+ Purge()
+}
+
+type cache struct {
+ cache *lru.Cache
+}
+
+// New instantiates and returns a new Cache which can hold up to the given
+// number of entries.
+func New(size int) Cache {
+ c, err := lru.New(size)
+
+ // instantiating the lru cache can't realistically fail
+ if err != nil {
+ panic(err)
+ }
+
+ return &cache{c}
+}
+
+func (c *cache) Get(key string) interface{} {
+ value, ok := c.cache.Get(key)
+ if !ok {
+ return nil
+ }
+
+ return value
+}
+
+func (c *cache) Set(key string, value interface{}) {
+ c.cache.Add(key, value)
+}
+
+func (c *cache) Purge() {
+ c.cache.Purge()
+}