Adding an in-memory cache to your API
We will incorporate an in-memory cache into our API to improve the performance. We will use the HashiCorp LRU cache library we saw earlier in the chapterto implement the store’s handleGetList method cache.
First of all, we need to define our LRU cache. We will use a global variable because I want to keep it simple, but you probably want to use another struct containing your application state:
var (
repository *Repository
allData = []ShopingList{}
listsCache lru.Cache
)
func main() {
var err error
listsCache, err = lru.New[string, ShopingList](128)
if err != nil {
fmt.Println("Unable to initialize the lists cache:", err.Error())
os.Exit(1)
}
...
This creates our LRU in-memory cache that we can use in the rest of our API. We need to modify our handleGetList method to use the cache. Let’s see how we can do that:
func handleGetList(w http.ResponseWriter, r *http.Request) {
id := r.PathValue...