Gin Memcached Middleware

If you are using gin to build a webservice, and you want to use memcached to store your data, you will search some articles about how to create a middleware to do that. After read some articles, I only found this middleware. But I got no luck. I cannot get a value from a key on one endpoint after I set it on another endpoint. So I didn’t use gin session and create my own middleware with gomemcache.

package main

import (

func MCMiddleware(mc *memcache.Client) gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Set("mem", mc)

func main() {
    r := gin.Default()

    mc := memcache.New("")


    r.GET("/set", func(c *gin.Context) {
        mem, _ := c.MustGet("mem").(*memcache.Client)
        mem.Set(&memcache.Item{Key: "somekey", Value: []byte("somevalue")})
        c.String(200, "ok\n")

    r.GET("/get", func(c *gin.Context) {
        mem, _ := c.MustGet("mem").(*memcache.Client)
        data, _ := mem.Get("somekey")
        c.String(200, string([]byte(data.Value))+"\n")


Then you can set and get a value from a key on all endpoints.

linx@crawler ~ $ curl localhost:8000/set
linx@crawler ~ $ curl localhost:8000/get

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *