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 (
    "github.com/gin-gonic/gin"
    "github.com/bradfitz/gomemcache/memcache"
)

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

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

    mc := memcache.New("127.0.0.1:11211")

    r.Use(MCMiddleware(mc))

    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")
    })

    r.Run(":8000")
}

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

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

You may also like

GO!

Leave a Reply

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