Golang: Using Memcached

This article was published 5 years ago. Due to the rapidly evolving world of technology, some concepts may no longer be applicable.

If you want to use memcached in a Golang project, the most recommended library is is memcache from Brad Fitzpatrick. Brad is both the author of memcache and a Golang core team member, which means that we can trust the library that he wrote.


First, we need to install the library:

go get github.com/bradfitz/gomemcache/memcache


Here’s the minimum you need to know to use memcached

Connect to memcache

mc := memcache.New("")
// => memcache.Client (http://godoc.org/github.com/bradfitz/gomemcache/memcache#Client)

Set a value

err := mc.Set(&memcache.Item{Key: "key_one", Value: []byte("michael")})
// => Error

Get a value

val, err := mc.Get("key_one")
// => memcache.Item, Error

Get multiple values

it, err := mc.GetMulti([]string{"key_one", "key_two"})
// => map[string]memcache.Item, Error

Putting it all together

Then we can write a small program to talk to our memcached server

package main

import (


func main() {

    // Connect to our memcache instance
    mc := memcache.New("")

    // Set some values
    mc.Set(&memcache.Item{Key: "key_one", Value: []byte("michael")})
    mc.Set(&memcache.Item{Key: "key_two", Value: []byte("programming")})

    // Get a single value
    val, err := mc.Get("key_one")

    if err != nil {

    fmt.Printf("-- %s", val.Value)

    // Get multiple values
    it, err := mc.GetMulti([]string{"key_one", "key_two"})

    if err != nil {

    // It's important to note here that `range` iterates in a *random* order
    for k, v := range it {
        fmt.Printf("## %s => %s\n", k, v.Value)


The return values from memcache will be wrapped in a memcache.Item type. You can find the documentation that shows it’s properties here

Thoughts on this post

kiran patil 2016-07-14

I am getting this error : dial tcp getsockopt: connection refused

michael 2016-07-15

You need to be running a memcached server on port 11211 (the default) on the same machine as your go code that you can connect to

Randy Hill 2017-03-16

I get this message “error memcache: connect timeout to xx.xx.xx.xxx:11111”

michael 2017-04-07

Check your memcache port – It’s 11211 by default, not 11111

Leave a comment?