Documentation ¶
Index ¶
- Constants
- Variables
- func AddCookie(ctx context.Context, cookie *http.Cookie, reclaim bool)
- func GetCookie(ctx context.Context, name string) string
- func IsValidCookieDomain(domain string) bool
- func RemoveCookie(ctx context.Context, config Config)
- type Config
- type Database
- type DestroyListener
- type Encoding
- type LifeTime
- type Marshaler
- type Session
- func (s *Session) Clear()
- func (s *Session) ClearFlashes()
- func (s *Session) Decrement(key string, n int) (newValue int)
- func (s *Session) Delete(key string) bool
- func (s *Session) DeleteFlash(key string)
- func (s *Session) Destroy()
- 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) GetBooleanDefault(key string, defaultValue bool) bool
- func (s *Session) GetFlash(key string) interface{}
- func (s *Session) GetFlashString(key string) string
- func (s *Session) GetFlashStringDefault(key string, defaultValue string) string
- func (s *Session) GetFlashes() map[string]interface{}
- func (s *Session) GetFloat32(key string) (float32, error)
- func (s *Session) GetFloat32Default(key string, defaultValue float32) float32
- func (s *Session) GetFloat64(key string) (float64, error)
- func (s *Session) GetFloat64Default(key string, defaultValue float64) float64
- func (s *Session) GetInt(key string) (int, error)
- func (s *Session) GetInt64(key string) (int64, error)
- func (s *Session) GetInt64Default(key string, defaultValue int64) int64
- func (s *Session) GetIntDefault(key string, defaultValue int) int
- func (s *Session) GetString(key string) string
- func (s *Session) GetStringDefault(key string, defaultValue string) string
- func (s *Session) HasFlash() bool
- func (s *Session) ID() string
- func (s *Session) Increment(key string, n int) (newValue int)
- 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) Visit(cb func(k string, v interface{}))
- type Sessions
- func (s *Sessions) Destroy(ctx context.Context)
- func (s *Sessions) DestroyAll()
- func (s *Sessions) DestroyByID(sid string)
- func (s *Sessions) OnDestroy(listeners ...DestroyListener)
- func (s *Sessions) ShiftExpiration(ctx context.Context)
- func (s *Sessions) Start(ctx context.Context) *Session
- func (s *Sessions) UpdateExpiration(ctx context.Context, expires time.Duration)
- func (s *Sessions) UseDatabase(db Database)
- type Transcoder
- type Unmarshaler
Constants ¶
const (
// DefaultCookieName the secret cookie's name for sessions
DefaultCookieName = "irissessionid"
)
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 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 GetCookie ¶
GetCookie returns cookie's value by it's name returns empty string if nothing was found
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 ¶
RemoveCookie deletes a cookie by it's name/key If "purge" is true then it removes the, temp, cookie from the request as well.
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.
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 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) DurationUntilExpiration ¶
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 ¶
HasExpired reports whether "lt" represents is expired.
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 (*Session) ClearFlashes ¶
func (s *Session) ClearFlashes()
ClearFlashes removes all flash messages.
func (*Session) Decrement ¶
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 ¶
Delete removes an entry by its key, returns true if actually something was removed.
func (*Session) DeleteFlash ¶
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) GetBoolean ¶
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 ¶
GetBooleanDefault same as `Get` but returns its boolean representation, if key doesn't exist then it returns the "defaultValue".
func (*Session) GetFlash ¶
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 ¶
GetFlashString same as `GetFlash` but returns its string representation, if key doesn't exist then it returns an empty string.
func (*Session) GetFlashStringDefault ¶
GetFlashStringDefault same as `GetFlash` but returns its string representation, if key doesn't exist then it returns the "defaultValue".
func (*Session) GetFlashes ¶
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 ¶
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 ¶
GetFloat32Default same as `Get` but returns its float32 representation, if key doesn't exist then it returns the "defaultValue".
func (*Session) GetFloat64 ¶
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 ¶
GetFloat64Default same as `Get` but returns its float64 representation, if key doesn't exist then it returns the "defaultValue".
func (*Session) GetInt ¶
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 ¶
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 ¶
GetInt64Default same as `Get` but returns its int64 representation, if key doesn't exist it returns the "defaultValue".
func (*Session) GetIntDefault ¶
GetIntDefault same as `Get` but returns its int representation, if key doesn't exist then it returns the "defaultValue".
func (*Session) GetString ¶
GetString same as Get but returns its string representation, if key doesn't exist then it returns an empty string.
func (*Session) GetStringDefault ¶
GetStringDefault same as Get but returns its string representation, if key doesn't exist then it returns the "defaultValue".
func (*Session) Increment ¶
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 ¶
IsNew returns true if this session is created by the current application's process.
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 ¶
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 New ¶
New returns a new fast, feature-rich sessions manager it can be adapted to an iris station
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) 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 ¶
ShiftExpiration move the expire date of a session to a new date by using session default timeout configuration.
func (*Sessions) UpdateExpiration ¶
UpdateExpiration 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, a session db doesn't have write access
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 ¶
Unmarshaler is the common unmarshaler interface, used by transcoder.