From c1c1bb2c4c1baf37dbcce96f144966d4ada65ac5 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Mon, 23 Jan 2023 22:30:30 +0100 Subject: Implement cache and logger middlewares for gemini --- src/cache/cache.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/cache/cache.go (limited to 'src/cache/cache.go') 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() +} -- cgit v1.2.3