sessions

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2016 License: MIT Imports: 12 Imported by: 0

README



Build Status License Releases Read me docs
Build Status Built with GoLang Platforms



Fast, unique & cross-framework http sessions for Go.
Easy to learn, while providing robust set of features.

Ideally suited for both experienced and novice Developers.

Quick view

import "gopkg.in/kataras/go-sessions.v0"

sess := sessions.Start(http.ResponseWriter, *http.Request)
sess.ID() string
sess.Get(string) interface{}
sess.GetString(key string) string
sess.GetInt(key string) (int, error)
sess.GetInt64(key string) (int64, error)
sess.GetFloat32(key string) (float32, error)
sess.GetFloat64(key string) (float64, error)
sess.GetBoolean(key string) (bool, error)
sess.GetAll() map[string]interface{}
sess.VisitAll(cb func(k string, v interface{}))
sess.Set(string, interface{})
sess.Delete(string)
sess.Clear()

Installation

The only requirement is the Go Programming Language, at least v1.7.

$ go get -u gopkg.in/kataras/go-sessions.v0

Features

  • Focus on simplicity and performance, it's the fastest sessions provider in Go world.
  • Cleans the temp memory when a session is idle, and re-allocates it to the temp memory when it's necessary.
  • The most used sessions are optimized to be in the front of the memory's list.
  • Supports any type of external database.
  • Works with both net/http and valyala/fasthttp.

Docs

Take a look at the ./examples.

OUTLINE

// Start starts the session for the particular net/http request
Start(http.ResponseWriter, *http.Request) Session
// Destroy kills the net/http session and remove the associated cookie
Destroy(http.ResponseWriter, *http.Request)

// Start starts the session for the particular valyala/fasthttp request
StartFasthttp(*fasthttp.RequestCtx) Session
// Destroy kills the valyala/fasthttp session and remove the associated cookie
DestroyFasthttp(*fasthttp.RequestCtx)

// UseDatabase ,optionally, adds a session database to the manager's provider,
// a session db doesn't have write access
// see https://github.com/kataras/go-sessions/tree/master/sessiondb
UseDatabase(Database)

// UpdateConfig updates the configuration field (Config does not receives a pointer, so this is a way to update a pre-defined configuration)
UpdateConfig(Config)

Usage NET/HTTP

Start returns a Session, Session outline

type Session interface {
  ID() string
  Get(string) interface{}
  GetString(key string) string
  GetInt(key string) (int, error)
  GetInt64(key string) (int64, error)
  GetFloat32(key string) (float32, error)
  GetFloat64(key string) (float64, error)
  GetBoolean(key string) (bool, error)
  GetAll() map[string]interface{}
  VisitAll(cb func(k string, v interface{}))
  Set(string, interface{})
  Delete(string)
  Clear()
}
package main

import (
	"fmt"
	"gopkg.in/kataras/go-sessions.v0"
	"net/http"
)

func main() {

	// set some values to the session
	setHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		values := map[string]interface{}{
			"Name":   "go-sessions",
			"Days":   "1",
			"Secret": "dsads£2132215£%%Ssdsa",
		}

		sess := sessions.Start(res, req) // init the session
    // sessions.Start returns the Session interface we saw before

		for k, v := range values {
			sess.Set(k, v) // fill session, set each of the key-value pair
		}
		res.Write([]byte("Session saved, go to /get to view the results"))
	})
	http.Handle("/set/", setHandler)

	// get the values from the session
	getHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		sess := sessions.Start(res, req) // init the session
		sessValues := sess.GetAll()      // get all values from this session

		res.Write([]byte(fmt.Sprintf("%#v", sessValues)))
	})
	http.Handle("/get/", getHandler)

	// clear all values from the session
	clearHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		sess := sessions.Start(res, req)
		sess.Clear()
	})
	http.Handle("/clear/", clearHandler)

	// destroys the session, clears the values and removes the server-side entry and client-side sessionid cookie
	destroyHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		sessions.Destroy(res, req)
	})
	http.Handle("/destroy/", destroyHandler)

	fmt.Println("Open a browser tab and navigate to the localhost:8080/set/")
	http.ListenAndServe(":8080", nil)
}

Usage FASTHTTP

StartFasthttp returns again Session, Session outline

type Session interface {
  ID() string
  Get(string) interface{}
  GetString(key string) string
  GetInt(key string) (int, error)
  GetInt64(key string) (int64, error)
  GetFloat32(key string) (float32, error)
  GetFloat64(key string) (float64, error)
  GetBoolean(key string) (bool, error)
  GetAll() map[string]interface{}
  VisitAll(cb func(k string, v interface{}))
  Set(string, interface{})
  Delete(string)
  Clear()
}
package main

import (
	"fmt"
	"gopkg.in/kataras/go-sessions.v0"
	"github.com/valyala/fasthttp"
)

func main() {

	// set some values to the session
	setHandler := func(reqCtx *fasthttp.RequestCtx) {
		values := map[string]interface{}{
			"Name":   "go-sessions",
			"Days":   "1",
			"Secret": "dsads£2132215£%%Ssdsa",
		}

		sess := sessions.StartFasthttp(reqCtx) // init the session
		// sessions.StartFasthttp returns the, same, Session interface we saw before too

		for k, v := range values {
			sess.Set(k, v) // fill session, set each of the key-value pair
		}
		reqCtx.WriteString("Session saved, go to /get to view the results")
	}

	// get the values from the session
	getHandler := func(reqCtx *fasthttp.RequestCtx) {
		sess := sessions.StartFasthttp(reqCtx) // init the session
		sessValues := sess.GetAll()    // get all values from this session

		reqCtx.WriteString(fmt.Sprintf("%#v", sessValues))
	}

	// clear all values from the session
	clearHandler := func(reqCtx *fasthttp.RequestCtx) {
		sess := sessions.StartFasthttp(reqCtx)
		sess.Clear()
	}

	// destroys the session, clears the values and removes the server-side entry and client-side sessionid cookie
	destroyHandler := func(reqCtx *fasthttp.RequestCtx) {
		sessions.DestroyFasthttp(reqCtx)
	}

	fmt.Println("Open a browser tab and navigate to the localhost:8080/set")
	fasthttp.ListenAndServe(":8080", func(reqCtx *fasthttp.RequestCtx) {
		path := string(reqCtx.Path())

		if path == "/set" {
			setHandler(reqCtx)
		} else if path == "/get" {
			getHandler(reqCtx)
		} else if path == "/clear" {
			clearHandler(reqCtx)
		} else if path == "/destroy" {
			destroyHandler(reqCtx)
		} else {
			reqCtx.WriteString("Please navigate to /set or /get or /clear or /destroy")
		}
	})
}


FAQ

If you'd like to discuss this package, or ask questions about it, feel free to

Versioning

Current: v0.0.6

Read more about Semantic Versioning 2.0.0

People

The author of go-sessions is @kataras.

Contributing

If you are interested in contributing to the go-sessions project, please make a PR.

License

This project is licensed under the MIT License.

License can be found here.

Documentation

Overview

Package sessions provides sessions support for net/http unique with auto-GC, register unlimited number of databases to Load and Update/Save the sessions in external server or to an external (no/or/and sql) database Usage net/http: // init a new sessions manager( if you use only one web framework inside your app then you can use the package-level functions like: sessions.Start/sessions.Destroy) manager := sessions.New(sessions.Config{}) // start a session for a particular client manager.Start(http.ResponseWriter, *http.Request)

// destroy a session from the server and client,

// don't call it on each handler, only on the handler you want the client to 'logout' or something like this:

manager.Destroy(http.ResponseWriter, *http.Request)

Usage valyala/fasthttp: // init a new sessions manager( if you use only one web framework inside your app then you can use the package-level functions like: sessions.Start/sessions.Destroy) manager := sessions.New(sessions.Config{}) // start a session for a particular client manager.StartFasthttp(*fasthttp.RequestCtx)

// destroy a session from the server and client,

// don't call it on each handler, only on the handler you want the client to 'logout' or something like this:

manager.DestroyFasthttp(*fasthttp.Request)

Note that, now, you can use both fasthttp and net/http within the same sessions manager(.New) instance! So now, you can share sessions between a net/http app and valyala/fasthttp app

Index

Constants

View Source
const (
	// DefaultCookieName the secret cookie's name for sessions
	DefaultCookieName = "gosessionsid"
	// DefaultGcDuration  is the default Session Manager's GCDuration , which is 2 hours
	DefaultGcDuration = time.Duration(2) * time.Hour
	// DefaultCookieExpires  is the default Session Manager's Cookie expire , which is 2 hours
	DefaultCookieExpires = DefaultGcDuration
	// DefaultCookieLength is the default Session Manager's CookieLength, which is 32
	DefaultCookieLength = 32
)
View Source
const (
	// Version current version number
	Version = "0.0.6"
)

Variables

View Source
var (
	// CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie.
	CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)

	// CookieExpireUnlimited indicates that the cookie doesn't expire.
	CookieExpireUnlimited = time.Now().AddDate(23, 0, 0)
)

Functions

func AcquireCookie

func AcquireCookie() *http.Cookie

AcquireCookie returns an empty Cookie object from the pool.

The returned object may be returned back to the pool with ReleaseCookie. This allows reducing GC load.

func AddCookie

func AddCookie(cookie *http.Cookie, res http.ResponseWriter)

AddCookie adds a cookie

func AddFasthttpCookie

func AddFasthttpCookie(c *fasthttp.Cookie, reqCtx *fasthttp.RequestCtx)

AddFasthttpCookie adds a cookie to the client

func Deserialize

func Deserialize(str string, m interface{}) error

Deserialize accepts an encoded string and a data struct which will be filled with the desierialized string using gob decoder

func Destroy

func Destroy(res http.ResponseWriter, req *http.Request)

Destroy kills the net/http session and remove the associated cookie

func DestroyFasthttp

func DestroyFasthttp(reqCtx *fasthttp.RequestCtx)

DestroyFasthttp kills the valyala/fasthttp session and remove the associated cookie

func GC

func GC()

GC tick-tock for the store cleanup, call it manually if you set the AutoStart configuration field to false. otherwise do not call it manually. it's running inside a new goroutine

func GenerateSessionID

func GenerateSessionID(length int) string

GenerateSessionID returns a random string, used to set the session id

func GetCookie

func GetCookie(name string, req *http.Request) string

GetCookie returns cookie's value by it's name returns empty string if nothing was found

func GetFasthttpCookie

func GetFasthttpCookie(name string, reqCtx *fasthttp.RequestCtx) (val string)

GetFasthttpCookie returns cookie's value by it's name returns empty string if nothing was found

func IsValidCookieDomain

func IsValidCookieDomain(domain string) bool

IsValidCookieDomain returns true if the receiver is a valid domain to set valid means that is recognised as 'domain' by the browser, so it(the cookie) can be shared with subdomains also

func Random

func Random(n int) []byte

Random takes a parameter (int) and returns random slice of byte ex: var randomstrbytes []byte; randomstrbytes = Random(32) note: this code doesn't belongs to me, but it works just fine*

func RandomString

func RandomString(n int) string

RandomString accepts a number(10 for example) and returns a random string using simple but fairly safe random algorithm

func ReleaseCookie

func ReleaseCookie(cookie *http.Cookie)

ReleaseCookie returns the Cookie object acquired with AcquireCookie back to the pool.

Do not access released Cookie object, otherwise data races may occur.

func RemoveCookie

func RemoveCookie(name string, res http.ResponseWriter, req *http.Request)

RemoveCookie deletes a cookie by it's name/key

func RemoveFasthttpCookie

func RemoveFasthttpCookie(name string, reqCtx *fasthttp.RequestCtx)

RemoveFasthttpCookie deletes a cookie by it's name/key

func Serialize

func Serialize(m interface{}) (string, error)

Serialize serialize any type to gob bytes and after returns its the base64 encoded string

func Set

func Set(setters ...OptionSetter)

Set options/configuration fields in runtime

func UseDatabase

func UseDatabase(db Database)

UseDatabase adds a session database to the manager's provider, a session db doesn't have write access

Types

type Config

type Config struct {
	// Cookie string, the session's client cookie name, for example: "mysessionid"
	//
	// Defaults to "gosessionid"
	Cookie string

	// DecodeCookie set it to true to decode the cookie key with base64 URLEncoding
	//
	// Defaults to false
	DecodeCookie bool

	// Expires the duration of which the cookie must expires (created_time.Add(Expires)).
	// If you want to delete the cookie when the browser closes, set it to -1 but in this case, the server side's session duration is up to GcDuration
	//
	// Defaults to infinitive/unlimited life duration(0)
	Expires time.Duration

	// CookieLength the length of the sessionid's cookie's value, let it to 0 if you don't want to change it
	//
	// Defaults to 32
	CookieLength int

	// GcDuration every how much duration(GcDuration) the memory should be clear for unused cookies (GcDuration)
	// for example: time.Duration(2)*time.Hour. it will check every 2 hours if cookie hasn't be used for 2 hours,
	// deletes it from backend memory until the user comes back, then the session continue to work as it was
	//
	// Defaults to 2 hours
	GcDuration time.Duration

	// DisableSubdomainPersistence set it to true in order dissallow your q subdomains to have access to the session cookie
	//
	// Defaults to false
	DisableSubdomainPersistence bool

	// DisableAutoGC disables the auto-gc running when the session manager is created
	// set to false to disable this behavior, you can call(onnce) manually the GC using the .GC function
	//
	// Defaults to false
	DisableAutoGC bool
}

Config the configuration for sessions has 7 fields first is the cookieName, the session's name (string) ["mysessionsecretcookieid"] second enable if you want to decode the cookie's key also third is the time which the client's cookie expires forth is the cookie length (sessionid) int, defaults to 32, do not change if you don't have any reason to do fifth is the gcDuration (time.Duration) when this time passes it removes the unused sessions from the memory until the user come back sixth is the DisableSubdomainPersistence which you can set it to true in order dissallow your q subdomains to have access to the session cook seventh is the AutoStart which defaults to true, disable it in order to disable the autostart- GC when the session manager is created

func (Config) Set

func (c Config) Set(main *Config)

Set implements the OptionSetter

func (Config) Validate

func (c Config) Validate() Config

Validate corrects missing fields configuration fields and returns the right configuration

type Database

type Database interface {
	Load(string) map[string]interface{}
	Update(string, map[string]interface{})
}

Database is the interface which all session databases should implement By design it doesn't support any type of cookie session like other frameworks, I want to protect you, believe me, no context access (although we could) The scope of the database is to session somewhere the sessions in order to keep them after restarting the server, nothing more. the values are sessiond by the underline session, the check for new sessions, or 'this session value should added' are made automatically by q, you are able just to set the values to your backend database with Load function. session database doesn't have any write or read access to the session, the loading of the initial data is done by the Load(string) map[string]interfface{} function synchronization are made automatically, you can register more than one session database but the first non-empty Load return data will be used as the session values.

type OptionSet

type OptionSet func(c *Config)

OptionSet implements the OptionSetter

func Cookie(val string) OptionSet

Cookie string, the session's client cookie name, for example: "mysessionid"

Defaults to "gosessionid"

func CookieLength

func CookieLength(val int) OptionSet

CookieLength the length of the sessionid's cookie's value, let it to 0 if you don't want to change it

Defaults to 32

func DecodeCookie

func DecodeCookie(val bool) OptionSet

DecodeCookie set it to true to decode the cookie key with base64 URLEncoding

Defaults to false

func DisableAutoGC

func DisableAutoGC(val bool) OptionSet

DisableAutoGC disables the auto-gc running when the session manager is created set to false to disable this behavior, you can call(onnce) manually the GC using the .GC function

Defaults to false

func DisableSubdomainPersistence

func DisableSubdomainPersistence(val bool) OptionSet

DisableSubdomainPersistence set it to true in order dissallow your q subdomains to have access to the session cookie

Defaults to false

func Expires

func Expires(val time.Duration) OptionSet

Expires the duration of which the cookie must expires (created_time.Add(Expires)). If you want to delete the cookie when the browser closes, set it to -1 but in this case, the server side's session duration is up to GcDuration

Defaults to infinitive/unlimited life duration(0)

func GcDuration

func GcDuration(val time.Duration) OptionSet

GcDuration every how much duration(GcDuration) the memory should be clear for unused cookies (GcDuration) for example: time.Duration(2)*time.Hour. it will check every 2 hours if cookie hasn't be used for 2 hours, deletes it from backend memory until the user comes back, then the session continue to work as it was

Defaults to 2 hours

func (OptionSet) Set

func (o OptionSet) Set(c *Config)

Set is the func which makes the OptionSet an OptionSetter, this is used mostly

type OptionSetter

type OptionSetter interface {
	// Set receives a pointer to the Config type and does the job of filling it
	Set(c *Config)
}

OptionSetter used as the type of return of a func which sets a configuration field's value

type Provider

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

Provider contains the sessions memory store and any external databases

func NewProvider

func NewProvider() *Provider

NewProvider returns a new sessions provider

func (*Provider) Destroy

func (p *Provider) Destroy(sid string)

Destroy destroys the session, removes all sessions values, the session itself and updates the registered session databases, this called from sessionManager which removes the client's cookie also.

func (*Provider) GC

func (p *Provider) GC(duration time.Duration)

GC clears the memory

func (*Provider) Init

func (p *Provider) Init(sid string, expires time.Duration) Session

Init creates the session and returns it

func (*Provider) NewSession

func (p *Provider) NewSession(sid string, expires time.Duration) Session

NewSession returns a new session from sessionid

func (*Provider) Read

func (p *Provider) Read(sid string, expires time.Duration) Session

Read returns the store which sid parameter is belongs

func (*Provider) RegisterDatabase

func (p *Provider) RegisterDatabase(db Database)

RegisterDatabase adds a session database a session db doesn't have write access

type Session

type Session interface {
	ID() string
	Get(string) interface{}
	GetString(key string) string
	GetInt(key string) (int, error)
	GetInt64(key string) (int64, error)
	GetFloat32(key string) (float32, error)
	GetFloat64(key string) (float64, error)
	GetBoolean(key string) (bool, error)
	GetAll() map[string]interface{}
	VisitAll(cb func(k string, v interface{}))
	Set(string, interface{})
	Delete(string)
	Clear()
}

Session is session's session interface, think it like a local store of each session's values implemented by the internal session iteral, normally the end-user will never use this interface. gettable by the provider -> sessions -> your app

func Start

func Start(res http.ResponseWriter, req *http.Request) Session

Start starts the session for the particular net/http request

func StartFasthttp

func StartFasthttp(reqCtx *fasthttp.RequestCtx) Session

StartFasthttp starts the session for the particular valyala/fasthttp request

type Sessions

type Sessions interface {
	// Set options/configuration fields in runtime
	Set(...OptionSetter)

	// UseDatabase ,optionally, adds a session database to the manager's provider,
	// a session db doesn't have write access
	// see https://github.com/kataras/go-sessions/tree/master/sessiondb
	UseDatabase(Database)

	// GC tick-tock for the store cleanup, call it manually if you set the AutoStart configuration field to false.
	// otherwise do not call it manually.
	// it's running inside a new goroutine
	GC()

	// Start starts the session for the particular net/http request
	Start(http.ResponseWriter, *http.Request) Session

	// Destroy kills the net/http session and remove the associated cookie
	Destroy(http.ResponseWriter, *http.Request)

	// StartFasthttp starts the session for the particular valyala/fasthttp request
	StartFasthttp(*fasthttp.RequestCtx) Session

	// DestroyFasthttp kills the valyala/fasthttp session and remove the associated cookie
	DestroyFasthttp(*fasthttp.RequestCtx)
}

Sessions is the start point of this package contains all the registered sessions and manages them

func New

func New(setters ...OptionSetter) Sessions

New creates & returns a new Sessions(manager) and start its GC (calls the .Init)

Directories

Path Synopsis
sessiondb

Jump to

Keyboard shortcuts

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