gsb

package module
v0.0.0-...-7e4375d Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2020 License: Apache-2.0 Imports: 13 Imported by: 0

README

gorilla-sessions-bigcache

Fork github.com/bradleypeabody/gorilla-sessions-memcache

Bigcache session support for Gorilla Web Toolkit.

Dependencies

The usual gorilla stuff:

go get github.com/gorilla/sessions

For an ASCII bigcache client:

go get "github.com/allegro/bigcache/v2"

Usage

package main

import (
  "fmt"
  "net/http"
  "time"

  "github.com/allegro/bigcache/v2"
  gsb "github.com/jtorz/gorilla-sessions-bigcache"
)

func main() {
  bigcacheClient, err := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute))
  if err != nil {
    panic(err)
  }
  store := gsb.NewBigcacheStore(bigcacheClient, "session_prefix_", []byte("secret"))
  runServer(store)
}

func runServer(store *gsb.BigcacheStore) {
  http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, "session-name")
    if err != nil {
      fmt.Fprintf(w, "Error: %v", err)
      return
    }
    fmt.Fprintf(w, "Got: %v", session)
  })

  http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, "session-name")
    if err != nil {
      fmt.Fprintf(w, "Error: %v", err)
      return
    }
    session.Values["foo"] = "bar"
    session.Values[42] = 43
    session.Save(r, w)
    fmt.Fprint(w, "ok")
  })
  http.ListenAndServe(":8080", nil)
}

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

package main

import (
  "fmt"
  "net/http"
  "time"

  "github.com/allegro/bigcache/v2"
  gsb "github.com/jtorz/gorilla-sessions-bigcache"
)

func main() {
  bigcacheClient, err := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute))
  if err != nil {
    panic(err)
  }
  store := gsb.NewBigCacherStoreWithValueStorer(gsb.NewGoBigcacher(bigcacheClient), &gsb.HeaderStorer{HeaderFieldName: "X-CUSTOM-HEADER"}, "session_prefix_", []byte
  runServer(store)
}

func runServer(store *gsb.BigcacheStore) {
  http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, "session-name")
    if err != nil {
      fmt.Fprintf(w, "Error: %v", err)
      return
    }
    fmt.Fprintf(w, "Got: %v", session)
  })

  http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, "session-name")
    if err != nil {
      fmt.Fprintf(w, "Error: %v", err)
      return
    }
    session.Values["foo"] = "bar"
    session.Values[42] = 43
    session.Save(r, w)
    fmt.Fprint(w, "ok")
  })
  http.ListenAndServe(":8080", nil)
}

Storage Methods

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

  • SecureCookie - uses the default securecookie encoding. Values are more secure as they are not readable from bigcache 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 := gsb.NewBigCacherStore(bigcacheClient, "session_prefix_", []byte("..."))
// do one of these:
store.StoreMethod = gsb.StoreMethodSecureCookie // default, more secure
store.StoreMethod = gsb.StoreMethodGob // faster
store.StoreMethod = gsb.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 BigcacheStore.

store := gsb.NewBigCacherStore(bigcacheClient, "session_prefix_", []byte("..."))
store.Logging = 1

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

Documentation

Overview

Package gsb session support for Gorilla Web Toolkit

Index

Examples

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 bigcache

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 BigCacher

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

BigCacher is the interface gsb uses to interact with the bigcache client

type BigcacheStore

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

BigcacheStore stores sessions in bigcache

func NewBigCacherStore

func NewBigCacherStore(client BigCacher, keyPrefix string, keyPairs ...[]byte) *BigcacheStore

NewBigCacherStore returns a new BigcacheStore. You need to provide the bigcache client that implements the BigCacher interface and an optional prefix for the keys we store

func NewBigCacherStoreWithValueStorer

func NewBigCacherStoreWithValueStorer(client BigCacher, valueStorer ValueStorer, keyPrefix string, keyPairs ...[]byte) *BigcacheStore

NewBigCacherStoreWithValueStorer returns a new BigcacheStore backed by a ValueStorer. You need to provide the bigcache client that implements the BigCacher 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 bigcache and get the session values.

func NewBigcacheStore

func NewBigcacheStore(client *bigcache.BigCache, keyPrefix string, keyPairs ...[]byte) *BigcacheStore

NewBigcacheStore returns a new BigcacheStore for the gobigcache client (github.com/allegro/bigcache). You also need to provider an optional prefix for the keys we store.

Example
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/allegro/bigcache/v2"
	gsb "github.com/jtorz/gorilla-sessions-bigcache"
)

func main() {
	bigcacheClient, err := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute))
	if err != nil {
		panic(err)
	}
	store := gsb.NewBigcacheStore(bigcacheClient, "session_prefix_", []byte("secret"))
	//store := gsb.NewBigCacherStoreWithValueStorer(gsb.NewGoBigcacher(bigcacheClient), &gsb.HeaderStorer{HeaderFieldName: "X-CUSTOM-HEADER"}, "session_prefix_", []byte("secret-key-goes-here"))
	runServer(store)
}

func runServer(store *gsb.BigcacheStore) {
	http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
		session, err := store.Get(r, "session-name")
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
			return
		}
		fmt.Fprintf(w, "Got: %v", session)
	})

	http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
		session, err := store.Get(r, "session-name")
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
			return
		}
		session.Values["foo"] = "bar"
		session.Values[42] = 43
		session.Save(r, w)
		fmt.Fprint(w, "ok")
	})
	http.ListenAndServe(":8080", nil)
}
Output:

func NewBigcacheStoreWithValueStorer

func NewBigcacheStoreWithValueStorer(client *bigcache.BigCache, valueStorer ValueStorer, keyPrefix string, keyPairs ...[]byte) *BigcacheStore

NewBigcacheStoreWithValueStorer returns a new BigcacheStore backed by a ValueStorer. You need to provide the gobigcache client (github.com/allegro/bigcache) 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 bigcache and get the session values.

func (*BigcacheStore) Get

func (s *BigcacheStore) 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 (*BigcacheStore) MaxLength

func (s *BigcacheStore) 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 BigcacheStore is 4096.

func (*BigcacheStore) New

func (s *BigcacheStore) 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 (*BigcacheStore) Save

Save adds a single session to the response.

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 bigcache

func NewDumbMemorySessionStore

func NewDumbMemorySessionStore() *DumbMemoryStore

NewDumbMemorySessionStore Sessions implemented with a dumb in-memory map and no expiration. Good for local development so you don't have to run bigcached 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 bigcached 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 GoBigcacher

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

GoBigcacher is a wrapper to the gobigcache client that implements the BigCacher interface

func NewGoBigcacher

func NewGoBigcacher(c *bigcache.BigCache) *GoBigcacher

NewGoBigcacher returns a wrapped gobigcache client that implements the BigCacher interface

func (*GoBigcacher) Get

func (gm *GoBigcacher) Get(key string) (string, error)

func (*GoBigcacher) Set

func (gm *GoBigcacher) Set(key, val string, 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 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