sessions

package module
v3.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2018 License: MIT Imports: 12 Imported by: 0

README



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

Fast http sessions manager for Go.
Simple API, while providing robust set of features such as immutability, expiration time (can be shifted), databases like badger and redis as back-end storage.

Quick view

import "github.com/kataras/go-sessions"

sess := sessions.Start(http.ResponseWriter, *http.Request)
sess.
  ID() string
  Get(string) interface{}
  HasFlash() bool
  GetFlash(string) interface{}
  GetFlashString(string) string
  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{}
  GetFlashes() map[string]interface{}
  VisitAll(cb func(k string, v interface{}))
  Set(string, interface{})
  SetImmutable(key string, value interface{})
  SetFlash(string, interface{})
  Delete(string)
  Clear()
  ClearFlashes()

Installation

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

$ go get -u github.com/kataras/go-sessions

Features

Documentation

Take a look at the ./examples folder.

Outline

// Start starts the session for the particular net/http request
Start(w http.ResponseWriter,r *http.Request) Session
// ShiftExpiration move the expire date of a session to a new date
// by using session default timeout configuration.
ShiftExpiration(w http.ResponseWriter, r *http.Request)
// UpdateExpiration change expire date of a session to a new date
// by using timeout value passed by `expires` receiver.
UpdateExpiration(w http.ResponseWriter, r *http.Request, expires time.Duration)
// Destroy kills the net/http session and remove the associated cookie
Destroy(w http.ResponseWriter,r  *http.Request)

// Start starts the session for the particular valyala/fasthttp request
StartFasthttp(ctx *fasthttp.RequestCtx) Session
// ShiftExpirationFasthttp move the expire date of a session to a new date
// by using session default timeout configuration.
ShiftExpirationFasthttp(ctx *fasthttp.RequestCtx)
// UpdateExpirationFasthttp change expire date of a session to a new date
// by using timeout value passed by `expires` receiver.
UpdateExpirationFasthttp(ctx *fasthttp.RequestCtx, expires time.Duration)
// Destroy kills the valyala/fasthttp session and remove the associated cookie
DestroyFasthttp(ctx *fasthttp.RequestCtx)

// DestroyByID removes the session entry
// from the server-side memory (and database if registered).
// Client's session cookie will still exist but it will be reseted on the next request.
//
// It's safe to use it even if you are not sure if a session with that id exists.
// Works for both net/http & fasthttp
DestroyByID(string)
// DestroyAll removes all sessions
// from the server-side memory (and database if registered).
// Client's session cookie will still exist but it will be reseted on the next request.
// Works for both net/http & fasthttp
DestroyAll()

// 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)

Configuration

// Config is the configuration for sessions. Please read it before using sessions.
Config struct {
	// Cookie string, the session's client cookie name, for example: "mysessionid"
	//
	// Defaults to "irissessionid".
	Cookie string

	// CookieSecureTLS set to true if server is running over TLS
	// and you need the session's cookie "Secure" field to be setted true.
	//
	// Note: The user should fill the Decode configuation field in order for this to work.
	// Recommendation: You don't need this to be setted to true, just fill the Encode and Decode fields
	// with a third-party library like secure cookie, example is provided at the _examples folder.
	//
	// Defaults to false.
	CookieSecureTLS bool

	// AllowReclaim will allow to
	// Destroy and Start a session in the same request handler.
	// All it does is that it removes the cookie for both `Request` and `ResponseWriter` while `Destroy`
	// or add a new cookie to `Request` while `Start`.
	//
	// Defaults to false.
	AllowReclaim bool

	// Encode the cookie value if not nil.
	// Should accept as first argument the cookie name (config.Cookie)
	//         as second argument the server's generated session id.
	// Should return the new session id, if error the session id setted to empty which is invalid.
	//
	// Note: Errors are not printed, so you have to know what you're doing,
	// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
	// You either need to provide exactly that amount or you derive the key from what you type in.
	//
	// Defaults to nil.
	Encode func(cookieName string, value interface{}) (string, error)
	// Decode the cookie value if not nil.
	// Should accept as first argument the cookie name (config.Cookie)
	//               as second second accepts the client's cookie value (the encoded session id).
	// Should return an error if decode operation failed.
	//
	// Note: Errors are not printed, so you have to know what you're doing,
	// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
	// You either need to provide exactly that amount or you derive the key from what you type in.
	//
	// Defaults to nil.
	Decode func(cookieName string, cookieValue string, v interface{}) error

	// Encoding same as Encode and Decode but receives a single instance which
	// completes the "CookieEncoder" interface, `Encode` and `Decode` functions.
	//
	// Defaults to nil.
	Encoding Encoding

	// 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.
	//
	// 0 means no expire, (24 years)
	// -1 means when browser closes
	// > 0 is the time.Duration which the session cookies should expire.
	//
	// Defaults to infinitive/unlimited life duration(0).
	Expires time.Duration

	// SessionIDGenerator should returns a random session id.
	// By default we will use a uuid impl package to generate
	// that, but developers can change that with simple assignment.
	SessionIDGenerator func() string

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

Usage NET/HTTP

Start returns a Session, Session outline

ID() string
Get(string) interface{}
HasFlash() bool
GetFlash(string) interface{}
GetString(key string) string
GetFlashString(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{}
GetFlashes() map[string]interface{}
VisitAll(cb func(k string, v interface{}))
Set(string, interface{})
SetImmutable(key string, value interface{})
SetFlash(string, interface{})
Delete(string)
Clear()
ClearFlashes()
package main

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

	"github.com/kataras/go-sessions"
)

type businessModel struct {
	Name string
}

func main() {
	app := http.NewServeMux()
	sess := sessions.New(sessions.Config{
		// Cookie string, the session's client cookie name, for example: "mysessionid"
		//
		// Defaults to "gosessionid"
		Cookie: "mysessionid",
		// it's time.Duration, from the time cookie is created, how long it can be alive?
		// 0 means no expire.
		// -1 means expire when browser closes
		// or set a value, like 2 hours:
		Expires: time.Hour * 2,
		// if you want to invalid cookies on different subdomains
		// of the same host, then enable it
		DisableSubdomainPersistence: false,
		// want to be crazy safe? Take a look at the "securecookie" example folder.
	})

	app.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(fmt.Sprintf("You should navigate to the /set, /get, /delete, /clear,/destroy instead")))
	})
	app.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {

		//set session values.
		s := sess.Start(w, r)
		s.Set("name", "iris")

		//test if setted here
		w.Write([]byte(fmt.Sprintf("All ok session setted to: %s", s.GetString("name"))))

		// Set will set the value as-it-is,
		// if it's a slice or map
		// you will be able to change it on .Get directly!
		// Keep note that I don't recommend saving big data neither slices or maps on a session
		// but if you really need it then use the `SetImmutable` instead of `Set`.
		// Use `SetImmutable` consistently, it's slower.
		// Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081
	})

	app.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
		// get a specific value, as string, if no found returns just an empty string
		name := sess.Start(w, r).GetString("name")

		w.Write([]byte(fmt.Sprintf("The name on the /set was: %s", name)))
	})

	app.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request) {
		// delete a specific key
		sess.Start(w, r).Delete("name")
	})

	app.HandleFunc("/clear", func(w http.ResponseWriter, r *http.Request) {
		// removes all entries
		sess.Start(w, r).Clear()
	})

	app.HandleFunc("/update", func(w http.ResponseWriter, r *http.Request) {
		// updates expire date
		sess.ShiftExpiration(w, r)
	})

	app.HandleFunc("/destroy", func(w http.ResponseWriter, r *http.Request) {

		//destroy, removes the entire session data and cookie
		sess.Destroy(w, r)
	})
	// Note about Destroy:
	//
	// You can destroy a session outside of a handler too, using the:
	// mySessions.DestroyByID
	// mySessions.DestroyAll

	// remember: slices and maps are muttable by-design
	// The `SetImmutable` makes sure that they will be stored and received
	// as immutable, so you can't change them directly by mistake.
	//
	// Use `SetImmutable` consistently, it's slower than `Set`.
	// Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081
	app.HandleFunc("/set_immutable", func(w http.ResponseWriter, r *http.Request) {
		business := []businessModel{{Name: "Edward"}, {Name: "value 2"}}
		s := sess.Start(w, r)
		s.SetImmutable("businessEdit", business)
		businessGet := s.Get("businessEdit").([]businessModel)

		// try to change it, if we used `Set` instead of `SetImmutable` this
		// change will affect the underline array of the session's value "businessEdit", but now it will not.
		businessGet[0].Name = "Gabriel"

	})

	app.HandleFunc("/get_immutable", func(w http.ResponseWriter, r *http.Request) {
		valSlice := sess.Start(w, r).Get("businessEdit")
		if valSlice == nil {
			w.Header().Set("Content-Type", "text/html; charset=UTF-8")
			w.Write([]byte("please navigate to the <a href='/set_immutable'>/set_immutable</a> first"))
			return
		}

		firstModel := valSlice.([]businessModel)[0]
		// businessGet[0].Name is equal to Edward initially
		if firstModel.Name != "Edward" {
			panic("Report this as a bug, immutable data cannot be changed from the caller without re-SetImmutable")
		}

		w.Write([]byte(fmt.Sprintf("[]businessModel[0].Name remains: %s", firstModel.Name)))

		// the name should remains "Edward"
	})

	http.ListenAndServe(":8080", app)
}

Usage FASTHTTP

StartFasthttp returns the same object as Start, Session.

ID() string
Get(string) interface{}
HasFlash() bool
GetFlash(string) interface{}
GetString(key string) string
GetFlashString(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{}
GetFlashes() map[string]interface{}
VisitAll(cb func(k string, v interface{}))
Set(string, interface{})
SetImmutable(key string, value interface{})
SetFlash(string, interface{})
Delete(string)
Clear()
ClearFlashes()

We have only one simple example because the API is the same, the returned session is the same for both net/http and valyala/fasthttp.

Just append the word "Fasthttp", the rest of the API remains as it's with net/http.

Start for net/http, StartFasthttp for valyala/fasthttp. ShiftExpiration for net/http, ShiftExpirationFasthttp for valyala/fasthttp. UpdateExpiration for net/http, UpdateExpirationFasthttp for valyala/fasthttp. Destroy for net/http, DestroyFasthttp for valyala/fasthttp.

package main

import (
	"fmt"

	"github.com/kataras/go-sessions"
	"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: v3.0.0

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 and valyala/fasthttp 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 = "gosessionid"
)
View Source
const (
	// Version current semantic version string of the go-sessions package.
	Version = "3.0.0"
)

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(24, 10, 10)
)
View Source
var Default = New(Config{}.Validate())

Default instance of the sessions, used for package-level functions.

View Source
var DefaultTranscoder = defaultTranscoder{}

DefaultTranscoder is the default transcoder across databases, it's the JSON by default. Change it if you want a different serialization/deserialization inside your session databases (when `UseDatabase` is used).

Functions

func AddCookie

func AddCookie(w http.ResponseWriter, r *http.Request, cookie *http.Cookie, reclaim bool)

AddCookie adds a cookie

func AddCookieFasthttp

func AddCookieFasthttp(ctx *fasthttp.RequestCtx, cookie *fasthttp.Cookie)

AddCookieFasthttp adds a cookie.

func Destroy

func Destroy(w http.ResponseWriter, r *http.Request)

Destroy remove the session data and remove the associated cookie.

func DestroyAll

func DestroyAll()

DestroyAll removes all sessions from the server-side memory (and database if registered). Client's session cookie will still exist but it will be reseted on the next request.

func DestroyByID

func DestroyByID(sid string)

DestroyByID removes the session entry from the server-side memory (and database if registered). Client's session cookie will still exist but it will be reseted on the next request.

It's safe to use it even if you are not sure if a session with that id exists.

Note: the sid should be the original one (i.e: fetched by a store ) it's not decoded.

func DestroyFasthttp

func DestroyFasthttp(ctx *fasthttp.RequestCtx)

DestroyFasthttp remove the session data and remove the associated cookie.

func GetCookie

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

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

func GetCookieFasthttp

func GetCookieFasthttp(ctx *fasthttp.RequestCtx, name string) (value string)

GetCookieFasthttp 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 OnDestroy

func OnDestroy(listeners ...DestroyListener)

OnDestroy registers one or more destroy listeners. A destroy listener is fired when a session has been removed entirely from the server (the entry) and client-side (the cookie). Note that if a destroy listener is blocking, then the session manager will delay respectfully, use a goroutine inside the listener to avoid that behavior.

func RemoveCookie

func RemoveCookie(w http.ResponseWriter, r *http.Request, config Config)

RemoveCookie deletes a cookie by it's name/key.

func RemoveCookieFasthttp

func RemoveCookieFasthttp(ctx *fasthttp.RequestCtx, config Config)

RemoveCookieFasthttp deletes a cookie by it's name/key.

func ShiftExpiration

func ShiftExpiration(w http.ResponseWriter, r *http.Request)

ShiftExpiration move the expire date of a session to a new date by using session default timeout configuration.

func ShiftExpirationFasthttp

func ShiftExpirationFasthttp(ctx *fasthttp.RequestCtx)

ShiftExpirationFasthttp move the expire date of a session to a new date by using session default timeout configuration.

func UpdateExpiration

func UpdateExpiration(w http.ResponseWriter, r *http.Request, expires time.Duration)

UpdateExpiration change expire date of a session to a new date by using timeout value passed by `expires` receiver.

func UpdateExpirationFasthttp

func UpdateExpirationFasthttp(ctx *fasthttp.RequestCtx, expires time.Duration)

UpdateExpirationFasthttp change expire date of a session to a new date by using timeout value passed by `expires` receiver.

func UseDatabase

func UseDatabase(db Database)

UseDatabase adds a session database to the manager's provider.

Types

type Config

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

	// CookieSecureTLS set to true if server is running over TLS
	// and you need the session's cookie "Secure" field to be setted true.
	//
	// Note: The user should fill the Decode configuation field in order for this to work.
	// Recommendation: You don't need this to be setted to true, just fill the Encode and Decode fields
	// with a third-party library like secure cookie, example is provided at the _examples folder.
	//
	// Defaults to false.
	CookieSecureTLS bool

	// AllowReclaim will allow to
	// Destroy and Start a session in the same request handler.
	// All it does is that it removes the cookie for both `Request` and `ResponseWriter` while `Destroy`
	// or add a new cookie to `Request` while `Start`.
	//
	// Defaults to false.
	AllowReclaim bool

	// Encode the cookie value if not nil.
	// Should accept as first argument the cookie name (config.Cookie)
	//         as second argument the server's generated session id.
	// Should return the new session id, if error the session id setted to empty which is invalid.
	//
	// Note: Errors are not printed, so you have to know what you're doing,
	// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
	// You either need to provide exactly that amount or you derive the key from what you type in.
	//
	// Defaults to nil.
	Encode func(cookieName string, value interface{}) (string, error)
	// Decode the cookie value if not nil.
	// Should accept as first argument the cookie name (config.Cookie)
	//               as second second accepts the client's cookie value (the encoded session id).
	// Should return an error if decode operation failed.
	//
	// Note: Errors are not printed, so you have to know what you're doing,
	// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
	// You either need to provide exactly that amount or you derive the key from what you type in.
	//
	// Defaults to nil.
	Decode func(cookieName string, cookieValue string, v interface{}) error

	// Encoding same as Encode and Decode but receives a single instance which
	// completes the "CookieEncoder" interface, `Encode` and `Decode` functions.
	//
	// Defaults to nil.
	Encoding Encoding

	// 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.
	//
	// 0 means no expire, (24 years)
	// -1 means when browser closes
	// > 0 is the time.Duration which the session cookies should expire.
	//
	// Defaults to infinitive/unlimited life duration(0).
	Expires time.Duration

	// SessionIDGenerator should returns a random session id.
	// By default we will use a uuid impl package to generate
	// that, but developers can change that with simple assignment.
	SessionIDGenerator func() string

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

Config is the configuration for sessions. Please read it before using sessions.

func (Config) Validate

func (c Config) Validate() Config

Validate corrects missing fields configuration fields and returns the right configuration

type Database

type Database interface {
	// Acquire receives a session's lifetime from the database,
	// if the return value is LifeTime{} then the session manager sets the life time based on the expiration duration lives in configuration.
	Acquire(sid string, expires time.Duration) LifeTime
	// Set sets a key value of a specific session.
	// The "immutable" input argument depends on the store, it may not implement it at all.
	Set(sid string, lifetime LifeTime, key string, value interface{}, immutable bool)
	// Get retrieves a session value based on the key.
	Get(sid string, key string) interface{}
	// Visit loops through all session keys and values.
	Visit(sid string, cb func(key string, value interface{}))
	// Len returns the length of the session's entries (keys).
	Len(sid string) int
	// Delete removes a session key value based on its key.
	Delete(sid string, key string) (deleted bool)
	// Clear removes all session key values but it keeps the session entry.
	Clear(sid string)
	// Release destroys the session, it clears and removes the session entry,
	// session manager will create a new session ID on the next request after this call.
	Release(sid string)
}

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. The scope of the database is to store somewhere the sessions in order to keep them after restarting the server, nothing more.

Synchronization are made automatically, you can register one using `UseDatabase`.

Look the `sessiondb` folder for databases implementations.

type DestroyListener

type DestroyListener func(sid string)

DestroyListener is the form of a destroy listener. Look `OnDestroy` for more.

type Encoding

type Encoding interface {
	// Encode the cookie value if not nil.
	// Should accept as first argument the cookie name (config.Name)
	//         as second argument the server's generated session id.
	// Should return the new session id, if error the session id setted to empty which is invalid.
	//
	// Note: Errors are not printed, so you have to know what you're doing,
	// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
	// You either need to provide exactly that amount or you derive the key from what you type in.
	//
	// Defaults to nil
	Encode(cookieName string, value interface{}) (string, error)
	// Decode the cookie value if not nil.
	// Should accept as first argument the cookie name (config.Name)
	//               as second second accepts the client's cookie value (the encoded session id).
	// Should return an error if decode operation failed.
	//
	// Note: Errors are not printed, so you have to know what you're doing,
	// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
	// You either need to provide exactly that amount or you derive the key from what you type in.
	//
	// Defaults to nil
	Decode(cookieName string, cookieValue string, v interface{}) error
}

Encoding is the Cookie Encoder/Decoder interface, which can be passed as configuration field alternatively to the `Encode` and `Decode` fields.

type Entry

type Entry struct {
	Key      string
	ValueRaw interface{}
	// contains filtered or unexported fields
}

Entry is the entry of the context storage Store - .Values()

func (Entry) BoolDefault

func (e Entry) BoolDefault(def bool) (bool, error)

BoolDefault returns the user's value as bool. a string which is "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False". Any other value returns an error.

If not found returns "def" and a non-nil error.

func (Entry) Float32Default

func (e Entry) Float32Default(key string, def float32) (float32, error)

Float32Default returns the entry's value as float32. If not found returns "def" and a non-nil error.

func (Entry) Float64Default

func (e Entry) Float64Default(def float64) (float64, error)

Float64Default returns the entry's value as float64. If not found returns "def" and a non-nil error.

func (Entry) GetByKindOrNil

func (e Entry) GetByKindOrNil(k reflect.Kind) interface{}

GetByKindOrNil will try to get this entry's value of "k" kind, if value is not that kind it will NOT try to convert it the "k", instead it will return nil, except if boolean; then it will return false even if the value was not bool.

If the "k" kind is not a string or int or int64 or bool then it will return the raw value of the entry as it's.

func (Entry) Int64Default

func (e Entry) Int64Default(def int64) (int64, error)

Int64Default returns the entry's value as int64. If not found returns "def" and a non-nil error.

func (Entry) IntDefault

func (e Entry) IntDefault(def int) (int, error)

IntDefault returns the entry's value as int. If not found returns "def" and a non-nil error.

func (Entry) String

func (e Entry) String() string

String returns the entry's value as string.

func (Entry) StringDefault

func (e Entry) StringDefault(def string) string

StringDefault returns the entry's value as string. If not found returns "def".

func (Entry) StringTrim

func (e Entry) StringTrim() string

StringTrim returns the entry's string value without trailing spaces.

func (Entry) Value

func (e Entry) Value() interface{}

Value returns the value of the entry, respects the immutable.

type LifeTime

type LifeTime struct {
	// Remember, tip for the future:
	// No need of gob.Register, because we embed the time.Time.
	// And serious bug which has a result of me spending my whole evening:
	// Because of gob encoding it doesn't encodes/decodes the other fields if time.Time is embedded
	// (this should be a bug(go1.9-rc1) or not. We don't care atm)
	time.Time
	// contains filtered or unexported fields
}

LifeTime controls the session expiration datetime.

func (*LifeTime) Begin

func (lt *LifeTime) Begin(d time.Duration, onExpire func())

Begin will begin the life based on the time.Now().Add(d). Use `Continue` to continue from a stored time(database-based session does that).

func (*LifeTime) DurationUntilExpiration

func (lt *LifeTime) DurationUntilExpiration() time.Duration

DurationUntilExpiration returns the duration until expires, it can return negative number if expired, a call to `HasExpired` may be useful before calling this `Dur` function.

func (*LifeTime) ExpireNow

func (lt *LifeTime) ExpireNow()

ExpireNow reduce the lifetime completely.

func (*LifeTime) HasExpired

func (lt *LifeTime) HasExpired() bool

HasExpired reports whether "lt" represents is expired.

func (*LifeTime) Revive

func (lt *LifeTime) Revive(onExpire func())

Revive will continue the life based on the stored Time. Other words that could be used for this func are: Continue, Restore, Resc.

func (*LifeTime) Shift

func (lt *LifeTime) Shift(d time.Duration)

Shift resets the lifetime based on "d".

type Marshaler

type Marshaler interface {
	Marshal(interface{}) ([]byte, error)
}

Marshaler is the common marshaler interface, used by transcoder.

type Session

type Session struct {
	Lifetime LifeTime
	// contains filtered or unexported fields
}

Session should expose the Sessions's end-user API. It is the session's storage controller which you can save or retrieve values based on a key.

This is what will be returned when sess := sessions.Start().

func Start

func Start(w http.ResponseWriter, r *http.Request) *Session

Start starts the session for the particular request.

func StartFasthttp

func StartFasthttp(ctx *fasthttp.RequestCtx) *Session

StartFasthttp starts the session for the particular request.

func (*Session) Clear

func (s *Session) Clear()

Clear removes all entries.

func (*Session) ClearFlashes added in v0.0.7

func (s *Session) ClearFlashes()

ClearFlashes removes all flash messages.

func (*Session) Decrement

func (s *Session) Decrement(key string, n int) (newValue int)

Decrement decrements the stored int value saved as "key" by -"n". If value doesn't exist on that "key" then it creates one with the "n" as its value. It returns the new, decremented, value even if it's less than zero.

func (*Session) Delete

func (s *Session) Delete(key string) bool

Delete removes an entry by its key, returns true if actually something was removed.

func (*Session) DeleteFlash added in v0.0.7

func (s *Session) DeleteFlash(key string)

DeleteFlash removes a flash message by its key.

func (*Session) Destroy

func (s *Session) Destroy()

Destroy destroys this session, it removes its session values and any flashes. This session entry will be removed from the server, the registered session databases will be notified for this deletion as well.

Note that this method does NOT remove the client's cookie, although it should be reseted if new session is attached to that (client).

Use the session's manager `Destroy(ctx)` in order to remove the cookie as well.

func (*Session) Get

func (s *Session) Get(key string) interface{}

Get returns a value based on its "key".

func (*Session) GetAll

func (s *Session) GetAll() map[string]interface{}

GetAll returns a copy of all session's values.

func (*Session) GetBoolean added in v0.0.6

func (s *Session) GetBoolean(key string) (bool, error)

GetBoolean same as `Get` but returns its boolean representation, if key doesn't exist then it returns false and a non-nil error.

func (*Session) GetBooleanDefault

func (s *Session) GetBooleanDefault(key string, defaultValue bool) bool

GetBooleanDefault same as `Get` but returns its boolean representation, if key doesn't exist then it returns the "defaultValue".

func (*Session) GetFlash added in v0.0.7

func (s *Session) GetFlash(key string) interface{}

GetFlash returns a stored flash message based on its "key" which will be removed on the next request.

To check for flash messages we use the HasFlash() Method and to obtain the flash message we use the GetFlash() Method. There is also a method GetFlashes() to fetch all the messages.

Fetching a message deletes it from the session. This means that a message is meant to be displayed only on the first page served to the user.

func (*Session) GetFlashString added in v0.0.7

func (s *Session) GetFlashString(key string) string

GetFlashString same as `GetFlash` but returns its string representation, if key doesn't exist then it returns an empty string.

func (*Session) GetFlashStringDefault

func (s *Session) GetFlashStringDefault(key string, defaultValue string) string

GetFlashStringDefault same as `GetFlash` but returns its string representation, if key doesn't exist then it returns the "defaultValue".

func (*Session) GetFlashes added in v0.0.7

func (s *Session) GetFlashes() map[string]interface{}

GetFlashes returns all flash messages as map[string](key) and interface{} value NOTE: this will cause at remove all current flash messages on the next request of the same user.

func (*Session) GetFloat32 added in v0.0.6

func (s *Session) GetFloat32(key string) (float32, error)

GetFloat32 same as `Get` but returns its float32 representation, if key doesn't exist then it returns -1 and a non-nil error.

func (*Session) GetFloat32Default

func (s *Session) GetFloat32Default(key string, defaultValue float32) float32

GetFloat32Default same as `Get` but returns its float32 representation, if key doesn't exist then it returns the "defaultValue".

func (*Session) GetFloat64 added in v0.0.6

func (s *Session) GetFloat64(key string) (float64, error)

GetFloat64 same as `Get` but returns its float64 representation, if key doesn't exist then it returns -1 and a non-nil error.

func (*Session) GetFloat64Default

func (s *Session) GetFloat64Default(key string, defaultValue float64) float64

GetFloat64Default same as `Get` but returns its float64 representation, if key doesn't exist then it returns the "defaultValue".

func (*Session) GetInt

func (s *Session) GetInt(key string) (int, error)

GetInt same as `Get` but returns its int representation, if key doesn't exist then it returns -1 and a non-nil error.

func (*Session) GetInt64 added in v0.0.6

func (s *Session) GetInt64(key string) (int64, error)

GetInt64 same as `Get` but returns its int64 representation, if key doesn't exist then it returns -1 and a non-nil error.

func (*Session) GetInt64Default

func (s *Session) GetInt64Default(key string, defaultValue int64) int64

GetInt64Default same as `Get` but returns its int64 representation, if key doesn't exist it returns the "defaultValue".

func (*Session) GetIntDefault

func (s *Session) GetIntDefault(key string, defaultValue int) int

GetIntDefault same as `Get` but returns its int representation, if key doesn't exist then it returns the "defaultValue".

func (*Session) GetString

func (s *Session) GetString(key string) string

GetString same as Get but returns its string representation, if key doesn't exist then it returns an empty string.

func (*Session) GetStringDefault

func (s *Session) GetStringDefault(key string, defaultValue string) string

GetStringDefault same as Get but returns its string representation, if key doesn't exist then it returns the "defaultValue".

func (*Session) HasFlash added in v0.0.7

func (s *Session) HasFlash() bool

HasFlash returns true if this session has available flash messages.

func (*Session) ID

func (s *Session) ID() string

ID returns the session's ID.

func (*Session) Increment

func (s *Session) Increment(key string, n int) (newValue int)

Increment increments the stored int value saved as "key" by +"n". If value doesn't exist on that "key" then it creates one with the "n" as its value. It returns the new, incremented, value.

func (*Session) IsNew

func (s *Session) IsNew() bool

IsNew returns true if this session is created by the current application's process.

func (*Session) PeekFlash

func (s *Session) PeekFlash(key string) interface{}

PeekFlash returns a stored flash message based on its "key". Unlike GetFlash, this will keep the message valid for the next requests, until GetFlashes or GetFlash("key").

func (*Session) Set

func (s *Session) Set(key string, value interface{})

Set fills the session with an entry "value", based on its "key".

func (*Session) SetFlash added in v0.0.7

func (s *Session) SetFlash(key string, value interface{})

SetFlash sets a flash message by its key.

A flash message is used in order to keep a message in session through one or several requests of the same user. It is removed from session after it has been displayed to the user. Flash messages are usually used in combination with HTTP redirections, because in this case there is no view, so messages can only be displayed in the request that follows redirection.

A flash message has a name and a content (AKA key and value). It is an entry of an associative array. The name is a string: often "notice", "success", or "error", but it can be anything. The content is usually a string. You can put HTML tags in your message if you display it raw. You can also set the message value to a number or an array: it will be serialized and kept in session like a string.

Flash messages can be set using the SetFlash() Method For example, if you would like to inform the user that his changes were successfully saved, you could add the following line to your Handler:

SetFlash("success", "Data saved!");

In this example we used the key 'success'. If you want to define more than one flash messages, you will have to use different keys.

func (*Session) SetImmutable

func (s *Session) SetImmutable(key string, value interface{})

SetImmutable fills the session with an entry "value", based on its "key". Unlike `Set`, the output value cannot be changed by the caller later on (when .Get) An Immutable entry should be only changed with a `SetImmutable`, simple `Set` will not work if the entry was immutable, for your own safety. Use it consistently, it's far slower than `Set`. Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081

func (*Session) Visit

func (s *Session) Visit(cb func(k string, v interface{}))

Visit loops each of the entries and calls the callback function func(key, value).

type Sessions

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

A Sessions manager should be responsible to Start a sesion, based on a Context, which should return a compatible Session interface, type. If the external session manager doesn't qualifies, then the user should code the rest of the functions with empty implementation.

Sessions should be responsible to Destroy a session based on the Context.

func New

func New(cfg Config) *Sessions

New returns the fast, feature-rich sessions manager.

func (*Sessions) Destroy

func (s *Sessions) Destroy(w http.ResponseWriter, r *http.Request)

Destroy remove the session data and remove the associated cookie.

func (*Sessions) DestroyAll

func (s *Sessions) DestroyAll()

DestroyAll removes all sessions from the server-side memory (and database if registered). Client's session cookie will still exist but it will be reseted on the next request.

func (*Sessions) DestroyByID

func (s *Sessions) DestroyByID(sid string)

DestroyByID removes the session entry from the server-side memory (and database if registered). Client's session cookie will still exist but it will be reseted on the next request.

It's safe to use it even if you are not sure if a session with that id exists.

Note: the sid should be the original one (i.e: fetched by a store ) it's not decoded.

func (*Sessions) DestroyFasthttp

func (s *Sessions) DestroyFasthttp(ctx *fasthttp.RequestCtx)

DestroyFasthttp remove the session data and remove the associated cookie.

func (*Sessions) OnDestroy

func (s *Sessions) OnDestroy(listeners ...DestroyListener)

OnDestroy registers one or more destroy listeners. A destroy listener is fired when a session has been removed entirely from the server (the entry) and client-side (the cookie). Note that if a destroy listener is blocking, then the session manager will delay respectfully, use a goroutine inside the listener to avoid that behavior.

func (*Sessions) ShiftExpiration

func (s *Sessions) ShiftExpiration(w http.ResponseWriter, r *http.Request)

ShiftExpiration move the expire date of a session to a new date by using session default timeout configuration.

func (*Sessions) ShiftExpirationFasthttp

func (s *Sessions) ShiftExpirationFasthttp(ctx *fasthttp.RequestCtx)

ShiftExpirationFasthttp move the expire date of a session to a new date by using session default timeout configuration.

func (*Sessions) Start

func (s *Sessions) Start(w http.ResponseWriter, r *http.Request) *Session

Start starts the session for the particular request.

func (*Sessions) StartFasthttp

func (s *Sessions) StartFasthttp(ctx *fasthttp.RequestCtx) *Session

StartFasthttp starts the session for the particular request.

func (*Sessions) UpdateExpiration

func (s *Sessions) UpdateExpiration(w http.ResponseWriter, r *http.Request, expires time.Duration)

UpdateExpiration change expire date of a session to a new date by using timeout value passed by `expires` receiver.

func (*Sessions) UpdateExpirationFasthttp

func (s *Sessions) UpdateExpirationFasthttp(ctx *fasthttp.RequestCtx, expires time.Duration)

UpdateExpirationFasthttp change expire date of a session to a new date by using timeout value passed by `expires` receiver.

func (*Sessions) UseDatabase

func (s *Sessions) UseDatabase(db Database)

UseDatabase adds a session database to the manager's provider.

type Store

type Store []Entry

Store is a collection of key-value entries with immutability capabilities. memstore contains a store which is just a collection of key-value entries with immutability capabilities.

Developers can use that storage to their own apps if they like its behavior. It's fast and in the same time you get read-only access (safety) when you need it.

func (*Store) Get

func (r *Store) Get(key string) interface{}

Get returns the entry's value based on its key. If not found returns nil.

func (*Store) GetBool

func (r *Store) GetBool(key string) (bool, error)

GetBool returns the user's value as bool, based on its key. a string which is "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False". Any other value returns an error.

If not found returns false and a non-nil error.

func (*Store) GetBoolDefault

func (r *Store) GetBoolDefault(key string, def bool) bool

GetBoolDefault returns the user's value as bool, based on its key. a string which is "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False".

If not found returns "def".

func (*Store) GetDefault

func (r *Store) GetDefault(key string, def interface{}) interface{}

GetDefault returns the entry's value based on its key. If not found returns "def". This function checks for immutability as well, the rest don't.

func (*Store) GetEntry

func (r *Store) GetEntry(key string) *Entry

GetEntry returns a pointer to the "Entry" found with the given "key" if nothing found then it returns nil, so be careful with that, it's not supposed to be used by end-developers.

func (*Store) GetFloat64

func (r *Store) GetFloat64(key string) (float64, error)

GetFloat64 returns the entry's value as float64, based on its key. If not found returns -1 and a non nil error.

func (*Store) GetFloat64Default

func (r *Store) GetFloat64Default(key string, def float64) float64

GetFloat64Default returns the entry's value as float64, based on its key. If not found returns "def".

func (*Store) GetInt

func (r *Store) GetInt(key string) (int, error)

GetInt returns the entry's value as int, based on its key. If not found returns -1 and a non-nil error.

func (*Store) GetInt64

func (r *Store) GetInt64(key string) (int64, error)

GetInt64 returns the entry's value as int64, based on its key. If not found returns -1 and a non-nil error.

func (*Store) GetInt64Default

func (r *Store) GetInt64Default(key string, def int64) int64

GetInt64Default returns the entry's value as int64, based on its key. If not found returns "def".

func (*Store) GetIntDefault

func (r *Store) GetIntDefault(key string, def int) int

GetIntDefault returns the entry's value as int, based on its key. If not found returns "def".

func (*Store) GetString

func (r *Store) GetString(key string) string

GetString returns the entry's value as string, based on its key.

func (*Store) GetStringDefault

func (r *Store) GetStringDefault(key string, def string) string

GetStringDefault returns the entry's value as string, based on its key. If not found returns "def".

func (*Store) GetStringTrim

func (r *Store) GetStringTrim(name string) string

GetStringTrim returns the entry's string value without trailing spaces.

func (*Store) Len

func (r *Store) Len() int

Len returns the full length of the entries.

func (*Store) Remove

func (r *Store) Remove(key string) bool

Remove deletes an entry linked to that "key", returns true if an entry is actually removed.

func (*Store) Reset

func (r *Store) Reset()

Reset clears all the request entries.

func (*Store) Save

func (r *Store) Save(key string, value interface{}, immutable bool) (Entry, bool)

Save same as `Set` However, if "immutable" is true then saves it as immutable (same as `SetImmutable`).

Returns the entry and true if it was just inserted, meaning that it will return the entry and a false boolean if the entry exists and it has been updated.

func (Store) Serialize

func (r Store) Serialize() []byte

Serialize returns the byte representation of the current Store.

func (*Store) Set

func (r *Store) Set(key string, value interface{}) (Entry, bool)

Set saves a value to the key-value storage. Returns the entry and true if it was just inserted, meaning that it will return the entry and a false boolean if the entry exists and it has been updated.

See `SetImmutable` and `Get`.

func (*Store) SetImmutable

func (r *Store) SetImmutable(key string, value interface{}) (Entry, bool)

SetImmutable saves a value to the key-value storage. Unlike `Set`, the output value cannot be changed by the caller later on (when .Get OR .Set)

An Immutable entry should be only changed with a `SetImmutable`, simple `Set` will not work if the entry was immutable, for your own safety.

Returns the entry and true if it was just inserted, meaning that it will return the entry and a false boolean if the entry exists and it has been updated.

Use it consistently, it's far slower than `Set`. Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081

func (*Store) Visit

func (r *Store) Visit(visitor func(key string, value interface{}))

Visit accepts a visitor which will be filled by the key-value objects.

type Transcoder

type Transcoder interface {
	Marshaler
	Unmarshaler
}

Transcoder is the interface that transcoders should implement, it includes just the `Marshaler` and the `Unmarshaler`.

type Unmarshaler

type Unmarshaler interface {
	Unmarshal([]byte, interface{}) error
}

Unmarshaler is the common unmarshaler interface, used by transcoder.

Directories

Path Synopsis
_examples
sessiondb

Jump to

Keyboard shortcuts

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