Package cache implements a simple LRU cache with generics.
It provides a mechanism for caching resources that are time consuming to create or retrieve. The main feature is that the creation process runs only once even when multiple go-routines concurrently request for a key that does not exist in the cache.
Originally implemented for a small web program that dynamically generates images based on the requested URI.
import (
"fmt"
"sync"
"time"
"github.com/tunabay/go-cache"
)
type MyResource struct {
data string
}
func CreateResource(key string) (*MyResource, time.Time, error) {
time.Sleep(time.Second >> 2) // slow creation
return &MyResource{data: "data " + key}, time.Time{}, nil
}
func main() {
myCache := cache.New[string, *MyResource](CreateResource)
showResource := func(key string) {
val, cached, _, err := myCache.Get(key)
if err != nil {
panic(err)
}
var tag string
if cached {
tag = " (cached)"
}
fmt.Printf("%s -> %q%s\n", key, val.data, tag)
}
var wg sync.WaitGroup
for i := 0; i < 12; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
key := fmt.Sprintf("key-%d", n&3)
showResource(key)
}(i)
}
wg.Wait()
}
- Read the documentation.
go-cache is available under the MIT license. See the LICENSE file for more information.