~netlandish/gobwebs

2540e45d2216a75769eece2038819c984197bacd — Peter Sanchez 3 months ago 95f6cf3
Adding basic cache documentation and set default limit for DummyCache if
no limit is given.

References: https://todo.code.netlandish.com/~netlandish/gobwebs/7
1 files changed, 17 insertions(+), 0 deletions(-)

M cache/cache.go
M cache/cache.go => cache/cache.go +17 -0
@@ 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,