This golang tutorial help to get and set go cache.The cache is use to get faster data and improve the performance.
Go Cache is a great in-memory caching package for golang that can help speed up your application. The Cache helps to bypass the parsing and minimizes web request to the server.
I am storing struct type data and, that hold array of object data.You can also use single data to set into golang cache.
I am assuming you have installed and configure golang, if not please configure using Golang Install in Windows
Install Go Cache in Golang
Let’s integrate go-cache with golang application.we will install go-cache package using by go command line as below –
go get github.com/patrickmn/go-cache
Instantiate Cache in Golang
We will create cache class instance and configure using already defined params, expiration time – After how much time cache will expire etc.We will add below method into app.go file.
package helper
import (
"github.com/patrickmn/go-cache"
"time"
"fmt"
"strings"
)
var Cache = cache.New(5*time.Minute, 5*time.Minute)
Let’s, we will define the Emp struct, that will use to map and save the cache object.
type Emp []struct {
ID int json:"id"
Name string json:"name"
}
How To Set Cache in Golang
The go-cache package is providing helper method to set the object or value into cache.I am using Get() method to set the value into cache key.
We will define SetCache method into app.go file, this file will takes two argument as a parameter, first one is cache key – against the value will save.The second one is the data which is interface type.
func SetCache(key string, emp interface{}) bool {
Cache.Set(key, emp, cache.NoExpiration)
return true
}
How To Get Cache in Golang
We have stored the data into go cache, Now we will fetch data from cache memory.I am using Get() method to get the value from cache.
We will define GetCache method into app.go file, This method will take cache as a parameter.
func GetCache(key string) (Emp, bool) {
var emp Emp
var found bool
data, found := Cache.Get(key)
if found {
emp = data.(Emp)
}
return emp, found
}