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
- Variables
- func AddCookie(w http.ResponseWriter, cookie *http.Cookie)
- func AddCookieFasthttp(ctx *fasthttp.RequestCtx, cookie *fasthttp.Cookie)
- func Destroy(w http.ResponseWriter, r *http.Request)
- func DestroyAll()
- func DestroyByID(sid string)
- func DestroyFasthttp(ctx *fasthttp.RequestCtx)
- func GetCookie(r *http.Request, name string) string
- func GetCookieFasthttp(ctx *fasthttp.RequestCtx, name string) (value string)
- func GobEncode(store Store, w io.Writer) error
- func GobSerialize(store Store) ([]byte, error)
- func IsValidCookieDomain(domain string) bool
- func RemoveCookie(w http.ResponseWriter, r *http.Request, name string)
- func RemoveCookieFasthttp(ctx *fasthttp.RequestCtx, name string)
- func ShiftExpiration(w http.ResponseWriter, r *http.Request)
- func ShiftExpirationFasthttp(ctx *fasthttp.RequestCtx)
- func UpdateExpiration(w http.ResponseWriter, r *http.Request, expires time.Duration)
- func UpdateExpirationFasthttp(ctx *fasthttp.RequestCtx, expires time.Duration)
- func UseDatabase(db Database)
- type Action
- type Config
- type Database
- type Entry
- type LifeTime
- type RemoteStore
- type Session
- func (s *Session) Clear()
- func (s *Session) ClearFlashes()
- func (s *Session) Delete(key string) bool
- func (s *Session) DeleteFlash(key string)
- func (s *Session) Get(key string) interface{}
- func (s *Session) GetAll() map[string]interface{}
- func (s *Session) GetBoolean(key string) (bool, error)
- func (s *Session) GetFlash(key string) interface{}
- func (s *Session) GetFlashString(key string) string
- func (s *Session) GetFlashes() map[string]interface{}
- func (s *Session) GetFloat32(key string) (float32, error)
- func (s *Session) GetFloat64(key string) (float64, error)
- func (s *Session) GetInt(key string) (int, error)
- func (s *Session) GetInt64(key string) (int64, error)
- func (s *Session) GetString(key string) string
- func (s *Session) HasFlash() bool
- func (s *Session) ID() string
- func (s *Session) IsNew() bool
- func (s *Session) PeekFlash(key string) interface{}
- func (s *Session) Set(key string, value interface{})
- func (s *Session) SetFlash(key string, value interface{})
- func (s *Session) SetImmutable(key string, value interface{})
- func (s *Session) VisitAll(cb func(k string, v interface{}))
- type Sessions
- func (s *Sessions) Destroy(w http.ResponseWriter, r *http.Request)
- func (s *Sessions) DestroyAll()
- func (s *Sessions) DestroyByID(sid string)
- func (s *Sessions) DestroyFasthttp(ctx *fasthttp.RequestCtx)
- func (s *Sessions) ShiftExpiration(w http.ResponseWriter, r *http.Request)
- func (s *Sessions) ShiftExpirationFasthttp(ctx *fasthttp.RequestCtx)
- func (s *Sessions) Start(w http.ResponseWriter, r *http.Request) *Session
- func (s *Sessions) StartFasthttp(ctx *fasthttp.RequestCtx) *Session
- func (s *Sessions) UpdateExpiration(w http.ResponseWriter, r *http.Request, expires time.Duration)
- func (s *Sessions) UpdateExpirationFasthttp(ctx *fasthttp.RequestCtx, expires time.Duration)
- func (s *Sessions) UseDatabase(db Database)
- type Store
- func (r *Store) Get(key string) interface{}
- func (r *Store) GetBool(key string) (bool, error)
- func (r *Store) GetBoolDefault(key string, def bool) (bool, error)
- func (r *Store) GetDefault(key string, def interface{}) interface{}
- func (r *Store) GetFloat64(key string) (float64, error)
- func (r *Store) GetFloat64Default(key string, def float64) (float64, error)
- func (r *Store) GetInt(key string) (int, error)
- func (r *Store) GetInt64(key string) (int64, error)
- func (r *Store) GetInt64Default(key string, def int64) (int64, error)
- func (r *Store) GetIntDefault(key string, def int) (int, error)
- func (r *Store) GetString(key string) string
- func (r *Store) GetStringDefault(key string, def string) string
- func (r *Store) GetStringTrim(name string) string
- func (r *Store) Len() int
- func (r *Store) Remove(key string) bool
- func (r *Store) Reset()
- func (r *Store) Save(key string, value interface{}, immutable bool) (Entry, bool)
- func (r Store) Serialize() []byte
- func (r *Store) Set(key string, value interface{}) (Entry, bool)
- func (r *Store) SetImmutable(key string, value interface{}) (Entry, bool)
- func (r *Store) Visit(visitor func(key string, value interface{}))
- type SyncPayload
Constants ¶
const (
// DefaultCookieName the secret cookie's name for sessions
DefaultCookieName = "gosessionid"
)
const (
// Version current semantic version string of the go-sessions package.
Version = "2.1.0"
)
Variables ¶
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) )
var Default = New(Config{}.Validate())
Default instance of the sessions, used for package-level functions.
var ErrIntParse = errors.New("unable to find or parse the integer, found: %#v")
ErrIntParse returns an error message when int parse failed it's not statical error, it depends on the failed value.
Functions ¶
func AddCookie ¶
func AddCookie(w http.ResponseWriter, cookie *http.Cookie)
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 ¶
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 GobSerialize ¶
GobSerialize same as GobEncode but it returns the bytes using a temp buffer.
func IsValidCookieDomain ¶
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 RemoveCookie ¶
func RemoveCookie(w http.ResponseWriter, r *http.Request, name string)
RemoveCookie deletes a cookie by it's name/key.
func RemoveCookieFasthttp ¶
func RemoveCookieFasthttp(ctx *fasthttp.RequestCtx, name string)
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 ¶
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 Action ¶
type Action uint32
Action reports the specific action that the memory store sends to the database.
const ( // ActionCreate occurs when add a key-value pair // on the database session entry for the first time. ActionCreate Action = iota // ActionInsert occurs when add a key-value pair // on the database session entry. ActionInsert // ActionUpdate occurs when modify an existing key-value pair // on the database session entry. ActionUpdate // ActionDelete occurs when delete a specific value from // a specific key from the database session entry. ActionDelete // ActionClear occurs when clear all values but keep the database session entry. ActionClear // ActionDestroy occurs when destroy, // destroy is the action when clear all and remove the session entry from the database. ActionDestroy )
type Config ¶
type Config struct { // Cookie string, the session's client cookie name, for example: "mysessionid" // // Defaults to "gosessionid" 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 // 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 func(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 func(cookieName string, cookieValue string, v interface{}) error // 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 review it well before using sessions.
type Database ¶
type Database interface { Load(sid string) RemoteStore Sync(p SyncPayload) }
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 more than one session database but the first non-empty Load return data will be used as the session values.
Note: Expiration on Load is up to the database, meaning that: the database can decide how to retrieve and parse the expiration datetime
I'll try to explain you the flow:
.Start -> if session database attached then load from that storage and save to the memory, otherwise load from memory. The load from database is done once on the initialize of each session. .Get (important) -> load from memory,
if database attached then it already loaded the values from database on the .Start action, so it will retrieve the data from the memory (fast)
.Set -> set to the memory, if database attached then update the storage .Delete -> clear from memory, if database attached then update the storage .Destroy -> destroy from memory and client cookie,
if database attached then update the storage with empty values, empty values means delete the storage with that specific session id.
Using everything else except memory is slower than memory but database is fetched once at each session and its updated on every Set, Delete, Destroy at call-time. All other external sessions managers out there work different than Iris one as far as I know, you may find them more suited to your application, it depends.
type Entry ¶
type Entry struct { Key string ValueRaw interface{} // contains filtered or unexported fields }
Entry is the entry of the context storage Store - .Values()
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 ¶
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) ExpireNow ¶
func (lt *LifeTime) ExpireNow()
ExpireNow reduce the lifetime completely.
func (*LifeTime) HasExpired ¶
HasExpired reports whether "lt" represents is expired.
type RemoteStore ¶
type RemoteStore struct { // Values contains the whole memory store, this store // contains the current, updated from memory calls, // session data (keys and values). This way // the database has access to the whole session's data // every time. Values Store // on insert it contains the expiration datetime // on update it contains the new expiration datetime(if updated or the old one) // on delete it will be zero // on clear it will be zero // on destroy it will be zero Lifetime LifeTime }
RemoteStore is a helper which is a wrapper for the store, it can be used as the session "table" which will be saved to the session database.
func DecodeRemoteStore ¶
func DecodeRemoteStore(b []byte) (store RemoteStore, err error)
DecodeRemoteStore accepts a series of bytes and returns the store.
func (RemoteStore) Serialize ¶
func (s RemoteStore) Serialize() ([]byte, error)
Serialize returns the byte representation of this RemoteStore.
type Session ¶
type Session struct {
// 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) ClearFlashes ¶ added in v0.0.7
func (s *Session) ClearFlashes()
ClearFlashes removes all flash messages.
func (*Session) Delete ¶
Delete removes an entry by its key, returns true if actually something was removed.
func (*Session) DeleteFlash ¶ added in v0.0.7
DeleteFlash removes a flash message by its key.
func (*Session) GetBoolean ¶ added in v0.0.6
GetBoolean same as Get but returns as boolean, if not found then returns -1 and an error
func (*Session) GetFlash ¶ added in v0.0.7
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
GetFlashString same as GetFlash but returns as string, if nil then returns an empty string.
func (*Session) GetFlashes ¶ added in v0.0.7
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
GetFloat32 same as Get but returns as float32, if not found then returns -1 and an error.
func (*Session) GetFloat64 ¶ added in v0.0.6
GetFloat64 same as Get but returns as float64, if not found then returns -1 and an error.
func (*Session) GetInt ¶
GetInt same as Get but returns as int, if not found then returns -1 and an error.
func (*Session) GetInt64 ¶ added in v0.0.6
GetInt64 same as Get but returns as int64, if not found then returns -1 and an error.
func (*Session) GetString ¶
GetString same as Get but returns as string, if nil then returns an empty string.
func (*Session) HasFlash ¶ added in v0.0.7
HasFlash returns true if this session has available flash messages.
func (*Session) PeekFlash ¶
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) SetFlash ¶ added in v0.0.7
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 ¶
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
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 (*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 ¶
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) 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) StartFasthttp ¶
func (s *Sessions) StartFasthttp(ctx *fasthttp.RequestCtx) *Session
StartFasthttp starts the session for the particular request.
func (*Sessions) UpdateExpiration ¶
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 ¶
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.
func (*Store) GetBool ¶
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.
func (*Store) GetBoolDefault ¶
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". Any other value returns an error.
If not found returns "def".
func (*Store) GetDefault ¶
GetDefault returns the entry's value based on its key. If not found returns "def".
func (*Store) GetFloat64 ¶
GetFloat64 returns the entry's value as float64, based on its key. If not found returns 0.0.
func (*Store) GetFloat64Default ¶
GetFloat64Default returns the entry's value as float64, based on its key. If not found returns "def".
func (*Store) GetInt ¶
GetInt returns the entry's value as int, based on its key. If not found returns 0.
func (*Store) GetInt64 ¶
GetInt64 returns the entry's value as int64, based on its key. If not found returns 0.0.
func (*Store) GetInt64Default ¶
GetInt64Default returns the entry's value as int64, based on its key. If not found returns "def".
func (*Store) GetIntDefault ¶
GetIntDefault returns the entry's value as int, based on its key. If not found returns "def".
func (*Store) GetStringDefault ¶
GetStringDefault returns the entry's value as string, based on its key. If not found returns "def".
func (*Store) GetStringTrim ¶
GetStringTrim returns the entry's string value without trailing spaces.
func (*Store) Remove ¶
Remove deletes an entry linked to that "key", returns true if an entry is actually removed.
func (*Store) Save ¶
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) Set ¶
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 ¶
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
type SyncPayload ¶
type SyncPayload struct { SessionID string Action Action // on insert it contains the new key and the value // on update it contains the existing key and the new value // on delete it contains the key (the value is nil) // on clear it contains nothing (empty key, value is nil) // on destroy it contains nothing (empty key, value is nil) Value Entry // Store contains the whole memory store, this store // contains the current, updated from memory calls, // session data (keys and values). This way // the database has access to the whole session's data // every time. Store RemoteStore }
SyncPayload reports the state of the session inside a database sync action.