Implementing caching in Go
Caching data in a web application is sometimes necessary to avoid requesting static data from a database or external service again and again. Go does not provide any built-in package to cache responses, but it does support it through external packages.
There are a number of packages, such as https://github.com/coocood/freecache and https://github.com/patrickmn/go-cache, which can help in implementing caching and, in this recipe, we will be using the https://github.com/patrickmn/go-cache to implement it.
How to do it…
- Install the
github.com/patrickmn/go-cachepackage using thego getcommand, as follows:
$ go get github.com/patrickmn/go-cache- Create
http-caching.go, where we will create a cache and populate it with data on server boot up, as follows:
package main
import
(
"fmt"
"log"
"net/http"
"time"
"github.com/patrickmn/go-cache"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
var newCache *cache.Cache
func init()
{
newCache = cache.New(5...