From 2540e45d2216a75769eece2038819c984197bacd Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Fri, 26 Jan 2024 07:11:34 -0600 Subject: [PATCH] Adding basic cache documentation and set default limit for DummyCache if no limit is given. References: https://todo.code.netlandish.com/~netlandish/gobwebs/7 --- cache/cache.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/cache/cache.go b/cache/cache.go index a5e2162..0505afa 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -1,21 +1,31 @@ +// Package cache implements an interface to work with cache backends + +// It is a very simple implementation. If you need/want more complex +// caching solutions then your own custom backend can have all the +// extras you'd like or simple use another caching interface in your +// project. package cache +// Cache is the interface to work with caching backends type Cache interface { Get(key string) (any, error) Set(key string, value any) (bool, error) Delete(key string) (bool, error) } +// DummyCache is a super dumb in memory cache store. type DummyCache struct { cache map[string]any limit int } +// Get fetches a specific key from the cache func (d *DummyCache) Get(key string) (any, error) { val := d.cache[key] return val, nil } +// Set will set a key/value in the cache backend. func (d *DummyCache) Set(key string, value any) (bool, error) { var evicted bool if len(d.cache) >= d.limit { @@ -31,6 +41,7 @@ func (d *DummyCache) Set(key string, value any) (bool, error) { return evicted, nil } +// Delete will delete a key from the cache func (d *DummyCache) Delete(key string) (bool, error) { var present bool if _, ok := d.cache[key]; ok { @@ -40,7 +51,13 @@ func (d *DummyCache) Delete(key string) (bool, error) { return present, nil } +// NewDummyCache will create a new DummyCache instance with the +// cache limit set to the value of `limit`. Default limit value +// is 10. func NewDummyCache(limit int) *DummyCache { + if limit == 0 { + limit = 10 + } return &DummyCache{ cache: make(map[string]any), limit: limit, -- 2.45.2