In Gin you can use the standard mc
interface to get and set values as described in our Go documentation to cache results of expensive computations or database queries:
package main
import (
"os"
"fmt"
"github.com/memcachier/mc"
)
func main() {
"MEMCACHIER_USERNAME")
username := os.Getenv("MEMCACHIER_PASSWORD")
password := os.Getenv("MEMCACHIER_SERVERS")
servers := os.Getenv(
mcClient := mc.NewMC(servers, username, password)defer mcClient.Quit()
"foo", "bar", 0, 0, 0)
_, err := mcClient.set(if err != nil {
"Failed to set value: %s\n", err)
fmt.Printf(
}
"foo")
val, _, _, err := c.Get(if err != nil {
"Failed to fetch value: %s\n", err)
fmt.Printf(
}"Got value: %s\n", val)
fmt.Printf( }
In addition there are two Gin specific ways to use Memcache:
To cache rendered views you need the gin-contrib/cache
library. Now you can use the CachePage
middleware like so:
package main
import (
"os"
"github.com/gin-gonic/gin"
"github.com/gin-contrib/cache"
"github.com/gin-contrib/cache/persistence"
)
func main() {
"MEMCACHIER_USERNAME")
username := os.Getenv("MEMCACHIER_PASSWORD")
password := os.Getenv("MEMCACHIER_SERVERS")
servers := os.Getenv(
mcStore := persistence.NewMemcachedBinaryStore(servers, username, password, persistence.FOREVER)
router := gin.New()"/", cache.CachePage(mcStore, persistence.DEFAULT, func(c *gin.Context) {
router.GET(// ...
})) }
Whenever the view changes, e.g., when the content changes, you need to make sure to invalidate the cached view so it will be re-rendered. This can be done by deleting the cached item (for the root
route in this case):
"/")) mcStore.Delete(cache.CreateKey(
Memcache works well for sessions that time out, however, since Memcache is a cache and thus not persistent, saving long-lived sessions in Memcache might not be ideal. For long-lived sessions consider a permanent storage option such as your database.
To use sessions in Gin you need gin-contrib/session
. You can easily add it to your Gin app like so:
package main
import (
"os"
"github.com/memcachier/mc"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memcached"
)
func main() {
"MEMCACHIER_USERNAME")
username := os.Getenv("MEMCACHIER_PASSWORD")
password := os.Getenv("MEMCACHIER_SERVERS")
servers := os.Getenv(
mcClient := mc.NewMC(servers, username, password)defer mcClient.Quit()
router := gin.New()"", []byte("secret"))
sessionStore := memcached.NewMemcacheStore(mcClient, "mysession", sessionStore))
router.Use(sessions.Sessions( }