This tutorial help to implement in-memory cache system into golang application.I am creating full-stack application, The front-end will use rest api to get and set data into cache.I am just sharing my thoughts to handle go-cache implementation.
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 using Go Cache package for caching in golang.
I will not use any golang framework, I just use mux and nagroni to handle routes.I am taking basic golang structure reference from below tutorial –
Golang MVC Project Structure without Any Framework
We will use following files into this golang cache application –
routes.go
: We will define routes information here.controller/cache.go
: here, We will define handler HTTP method.helper/helper.go
: This file will contains all go cache helper method.
How To Configure 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 params, Like expiration time – After how much time cache will expire etc.We will add below method into helper.go
file.
package helper import ( "github.com/patrickmn/go-cache" "time" "fmt" "strings" ) var Cache = cache.New(5*time.Minute, 5*time.Minute) type Emp []struct { ID int `json:"id"` Name string `json:"name"` }
Also, we have defined the Emp struct, that will use to map and save the cache object.
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.
Create Rest Routes Entry
We will make one entry into routes.go
file, that will be use to expose end point to the end user.
apiV1.Handle("/save-cache", controller.SaveCache).Methods("POST")
Create POST type end point to save data into cache.The /save-cache
end point will be handle by SaveCache
method.
Create Handler Method into Controller
Let’s create handler method into controller package, this will take the posted data as a parameters and set into the cache.
package controller import ( "fmt" "helper" "logger" "net/http" "encoding/json" _"reflect" ) var SaveCache = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var emp helper.Emp decoder := json.NewDecoder(r.Body) err := decoder.Decode(&emp) if err != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Error saving cache") logger.Log.Error(err) return } helper.SetCache("emp_data", emp) w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "successfully! data has been saved in cache") })
Above code, Created emp variable of helper.Emp
type. I am using SetCache
method to set the object value into cache, we will define SetCache
into helper package.
Define Helper Method To Set cache in Go
We will define SetCache
method into helper.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.
Create Rest End Point Into Routes File
We will make one entry into routes.go
file, The below end point will be use for to get data from cache.
apiV1.Handle("/get-cache", controller.GetCache).Methods("GET")
Create GET type Rest Call to fetch data from cache.The /get-cache
end point will be handle by GetCache
method.
Create Handler Method into Controller
Let’s create handler method into controller package, The GetCache
method responsible for fetch data from cache based on passed key.
var GetCache = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { data, found := helper.GetCache("emp_data") if found { fmt.Println(data) w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "successfully! data has been saved in cache") } else { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Error! Not found key into cache") return } })
Above code, I am using GetCache
method to get the object value from cache, The SetCache
define into helper package.
Define Helper Method To Get cache in Go
We will define GetCache
method into helper.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 }
The post How To Set and Get Cache Using Golang Rest Api appeared first on Rest Api Example.