Home

Awesome

gorilla-sessions-memcache

Memcache session support for Gorilla Web Toolkit.

Dependencies

The usual gorilla stuff:

go get github.com/gorilla/sessions

For an ASCII memcache client:

go get github.com/bradfitz/gomemcache/memcache

For a binary memcache client with SASL authentication:

go get github.com/memcachier/mc/v3

Usage

import (
  "github.com/bradfitz/gomemcache/memcache"
  // or
  "github.com/memcachier/mc/v3"
  gsm "github.com/bradleypeabody/gorilla-sessions-memcache"
)

...

// set up your memcache client
memcacheClient := gsm.NewGoMemcacher(memcache.New("localhost:11211"))
// or
memcacheClient := mc.NewMC("localhost:11211", "username", "password")

// set up your session store
store := gsm.NewMemcacherStore(memcacheClient, "session_prefix_", []byte("secret-key-goes-here"))

// and the rest of it is the same as any other gorilla session handling:
func MyHandler(w http.ResponseWriter, r *http.Request) {
  session, _ := store.Get(r, "session-name")
  session.Values["foo"] = "bar"
  session.Values[42] = 43
  session.Save(r, w)
}


...
// you can also setup a MemCacheStore, which does not rely on the browser accepting cookies.
// this means, your client has to extract and send a configurable http Headerfield manually.
// e.g.

// set up your memcache client
memcacheClient := gsm.NewGoMemcacher(memcache.New("localhost:11211"))
// or
memcacheClient := mc.NewMC("localhost:11211", "username", "password")

// set up your session store relying on a http Headerfield: `X-CUSTOM-HEADER`
store := gsm.NewMemcacherStoreWithValueStorer(memcacheClient, &gsm.HeaderStorer{HeaderFieldName:"X-CUSTOM-HEADER"}, "session_prefix_", []byte("secret-key-goes-here"))

// and the rest of it is the same as any other gorilla session handling:
// The client has to send the session information in the header-field: `X-CUSTOM-HEADER`
func MyHandler(w http.ResponseWriter, r *http.Request) {
  session, _ := store.Get(r, "session-name")
  session.Values["foo"] = "bar"
  session.Values[42] = 43
  session.Save(r, w)
}

Storage Methods

I've added a few different methods of storage of the session data in memcache. You use them by setting the StoreMethod field.

Example:

store := gsm.NewMemcacherStore(memcacheClient, "session_prefix_", []byte("..."))
// do one of these:
store.StoreMethod = gsm.StoreMethodSecureCookie // default, more secure
store.StoreMethod = gsm.StoreMethodGob // faster
store.StoreMethod = gsm.StoreMethodJson // human readable
							// (but watch out, it munches your types
							// to JSON compatible stuff)

Logging

Logging is available by setting the Logging field to > 0 after making your MemcacheStore.

store := gsm.NewMemcacherStore(memcacheClient, "session_prefix_", []byte("..."))
store.Logging = 1

That will output (using log.Printf) data about each session read/written from/to memcache. Useful for debugging

Things to Know