gsm

package module
v0.0.0-...-659414f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2018 License: Apache-2.0 Imports: 13 Imported by: 45

README

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

Usage

import (
  "github.com/bradfitz/gomemcache/memcache"
  // or
  "github.com/memcachier/mc"
  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.

  • SecureCookie - uses the default securecookie encoding. Values are more secure as they are not readable from memcache without the secret key.
  • Gob - uses the Gob encoder directly without any post processing. Faster. Result is Gob's usual binary gibber (not human readable)
  • Json - uses the Json Marshaller. Result is human readable, slower but still pretty fast. Be careful - it will munch your data into stuff that works with JSON, and the keys must be strings. Example: you put in an int64 value and you'll get back a float64.

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

  • No official release has been done of this package but it should be stable for production use.

  • You can also call NewDumbMemorySessionStore() for local development without a memcache server (it's a stub that just stuffs your session data in a map - definitely do not use this for anything but local dev and testing).

Documentation

Overview

Memcache session support for Gorilla Web Toolkit, without Google App Engine dependency.

Index

Constants

View Source
const (
	StoreMethodSecureCookie = StoreMethod("securecookie") // security
	StoreMethodGob          = StoreMethod("gob")          // speed
	StoreMethodJson         = StoreMethod("json")         // simplicity; warning: only string keys allowed and rest of data must be JSON.Marshal compatible
)

take your pick on how to store the values in memcache

Variables

View Source
var (
	// ErrHeaderFieldNameEmpty is returned, if the HeaderFieldName, which should be used to store session information, is empty.
	ErrHeaderFieldNameEmpty = errors.New("header fieldname empty")

	// ErrValueNotFound is returned, if no value was found for a given sessionName.
	ErrValueNotFound = errors.New("value not found")
)

Functions

This section is empty.

Types

type CookieStorer

type CookieStorer struct{}

CookieStorer is a ValueStorer, which stores values inside an http.Cookie

func (*CookieStorer) GetValueForSessionName

func (s *CookieStorer) GetValueForSessionName(r *http.Request, name string) (string, error)

GetValueForSessionName gets a value string from an http.Cookie, which should be present in the http.Request.

func (*CookieStorer) SetValueForSessionName

func (s *CookieStorer) SetValueForSessionName(w http.ResponseWriter, name, value string, options *sessions.Options) error

SetValueForSessionName sets a value string by creating a new http.Cookie and setting a `Set-Cookie` header

type DumbMemoryStore

type DumbMemoryStore struct {
	Codecs      []securecookie.Codec
	Options     *sessions.Options // default configuration
	Data        map[string]string // session data goes here
	ValueStorer ValueStorer
}

DumbMemoryStore stores sessions in memcache

func NewDumbMemorySessionStore

func NewDumbMemorySessionStore() *DumbMemoryStore

Sessions implemented with a dumb in-memory map and no expiration. Good for local development so you don't have to run memcached on your laptop just to fire up your app and hack away.

func NewDumbMemorySessionStoreWithValueStorer

func NewDumbMemorySessionStoreWithValueStorer(valueStorer ValueStorer) *DumbMemoryStore

NewDumbMemorySessionStoreWithValueStorer return a new dumb in-memory map and no expiration backed by a ValueStorer. Good for local development so you don't have to run memcached on your laptop just to fire up your app and hack away. A ValueStorer is used to store an encrypted sessionID. The encrypted sessionID is used to access the dumb in-memory map and get the session values.

func (*DumbMemoryStore) Get

func (s *DumbMemoryStore) Get(r *http.Request, name string) (*sessions.Session, error)

Get returns a session for the given name after adding it to the registry.

See CookieStore.Get().

func (*DumbMemoryStore) MaxLength

func (s *DumbMemoryStore) MaxLength(l int)

MaxLength restricts the maximum length of new sessions to l. If l is 0 there is no limit to the size of a session, use with caution. The default for a new DumbMemoryStore is 4096.

func (*DumbMemoryStore) New

func (s *DumbMemoryStore) New(r *http.Request, name string) (*sessions.Session, error)

New returns a session for the given name without adding it to the registry.

See CookieStore.New().

func (*DumbMemoryStore) Save

Save adds a single session to the response.

type GoMemcacher

type GoMemcacher struct {
	// contains filtered or unexported fields
}

GoMemcacher is a wrapper to the gomemcache client that implements the Memcacher interface

func NewGoMemcacher

func NewGoMemcacher(c *memcache.Client) *GoMemcacher

NewGoMemcacher returns a wrapped gomemcache client that implements the Memcacher interface

func (*GoMemcacher) Get

func (gm *GoMemcacher) Get(key string) (val string, flags uint32, cas uint64, err error)

func (*GoMemcacher) Set

func (gm *GoMemcacher) Set(key, val string, flags, exp uint32, ocas uint64) (cas uint64, err error)

type HeaderStorer

type HeaderStorer struct {
	HeaderFieldName string
}

HeaderStorer is a ValueStorer, which stores values inside an http Header. The key of the header contains can be configured using the `HeaderFieldName` variable. The header value is a Base64 encoded JSON map, whereas the keys of the map are the sessionName.

func (*HeaderStorer) GetValueForSessionName

func (s *HeaderStorer) GetValueForSessionName(r *http.Request, name string) (string, error)

GetValueForSessionName gets a value string from an http.Header.

func (*HeaderStorer) SetValueForSessionName

func (s *HeaderStorer) SetValueForSessionName(w http.ResponseWriter, name, value string, options *sessions.Options) error

SetValueForSessionName sets a value string by creating a new http.Header using the header key given by the headerStorer.HeaderKey function.

type MemcacheStore

type MemcacheStore struct {
	Codecs      []securecookie.Codec
	Options     *sessions.Options // default configuration
	Client      Memcacher
	KeyPrefix   string
	Logging     int // set to > 0 to enable logging (using log.Printf)
	StoreMethod StoreMethod
	ValueStorer ValueStorer
}

MemcacheStore stores sessions in memcache

func NewMemcacheStore

func NewMemcacheStore(client *memcache.Client, keyPrefix string, keyPairs ...[]byte) *MemcacheStore

NewMemcacheStore returns a new MemcacheStore for the gomemcache client (github.com/bradfitz/gomemcache/memcache). You also need to provider an optional prefix for the keys we store.

func NewMemcacheStoreWithValueStorer

func NewMemcacheStoreWithValueStorer(client *memcache.Client, valueStorer ValueStorer, keyPrefix string, keyPairs ...[]byte) *MemcacheStore

NewMemcacheStoreWithValueStorer returns a new MemcacheStore backed by a ValueStorer. You need to provide the gomemcache client (github.com/bradfitz/gomemcache/memcache) and an optional prefix for the keys we store. A ValueStorer is used to store an encrypted sessionID. The encrypted sessionID is used to access memcache and get the session values.

func NewMemcacherStore

func NewMemcacherStore(client Memcacher, keyPrefix string, keyPairs ...[]byte) *MemcacheStore

NewMemcacherStore returns a new MemcacheStore. You need to provide the memcache client that implements the Memcacher interface and an optional prefix for the keys we store

func NewMemcacherStoreWithValueStorer

func NewMemcacherStoreWithValueStorer(client Memcacher, valueStorer ValueStorer, keyPrefix string, keyPairs ...[]byte) *MemcacheStore

NewMemcacheStoreWithValueStorer returns a new MemcacheStore backed by a ValueStorer. You need to provide the memcache client that implements the Memcacher interface and an optional prefix for the keys we store. A ValueStorer is used to store an encrypted sessionID. The encrypted sessionID is used to access memcache and get the session values.

func (*MemcacheStore) Get

func (s *MemcacheStore) Get(r *http.Request, name string) (*sessions.Session, error)

Get returns a session for the given name after adding it to the registry.

See CookieStore.Get().

func (*MemcacheStore) MaxLength

func (s *MemcacheStore) MaxLength(l int)

MaxLength restricts the maximum length of new sessions to l. If l is 0 there is no limit to the size of a session, use with caution. The default for a new MemcacheStore is 4096.

func (*MemcacheStore) New

func (s *MemcacheStore) New(r *http.Request, name string) (*sessions.Session, error)

New returns a session for the given name without adding it to the registry.

See CookieStore.New().

func (*MemcacheStore) Save

Save adds a single session to the response.

type Memcacher

type Memcacher interface {
	Get(key string) (val string, flags uint32, cas uint64, err error)
	Set(key, val string, flags, exp uint32, ocas uint64) (cas uint64, err error)
}

Memcacher is the interface gsm uses to interact with the memcache client

type StoreMethod

type StoreMethod string

type ValueStorer

type ValueStorer interface {
	// GetValueForSessionName gets a value string using it's underlying ValueStorer implementation.
	GetValueForSessionName(r *http.Request, name string) (string, error)

	// SetValueForSessionName sets a value string using it's underlying ValueStorer implementation.
	SetValueForSessionName(w http.ResponseWriter, name, value string, options *sessions.Options) error
}

ValueStorer stores a value for a given name inside a http.Request. The value is typically the encrypted sessionID, which can then be fetched by a Gorialla sessions.Store implementation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL