Documentation ¶
Overview ¶
Package sessions provides sessions support for net/http unique with auto-GC, register unlimited number of databases to Load and Update/Save the sessions in external server or to an external (no/or/and sql) database Usage net/http: // init a new sessions manager( if you use only one web framework inside your app then you can use the package-level functions like: sessions.Start/sessions.Destroy) manager := sessions.New(sessions.Config{}) // start a session for a particular client manager.Start(http.ResponseWriter, *http.Request)
// destroy a session from the server and client,
// don't call it on each handler, only on the handler you want the client to 'logout' or something like this:
manager.Destroy(http.ResponseWriter, *http.Request)
Usage valyala/fasthttp: // init a new sessions manager( if you use only one web framework inside your app then you can use the package-level functions like: sessions.Start/sessions.Destroy) manager := sessions.New(sessions.Config{}) // start a session for a particular client manager.StartFasthttp(*fasthttp.RequestCtx)
// destroy a session from the server and client,
// don't call it on each handler, only on the handler you want the client to 'logout' or something like this:
manager.DestroyFasthttp(*fasthttp.Request)
Note that, now, you can use both fasthttp and net/http within the same sessions manager(.New) instance! So now, you can share sessions between a net/http app and valyala/fasthttp app
Index ¶
- Constants
- Variables
- func AcquireCookie() *http.Cookie
- func AddCookie(cookie *http.Cookie, res http.ResponseWriter)
- func AddFasthttpCookie(c *fasthttp.Cookie, reqCtx *fasthttp.RequestCtx)
- func Deserialize(str string, m interface{}) error
- func Destroy(res http.ResponseWriter, req *http.Request)
- func DestroyFasthttp(reqCtx *fasthttp.RequestCtx)
- func GC()
- func GenerateSessionID(length int) string
- func GetCookie(name string, req *http.Request) string
- func GetFasthttpCookie(name string, reqCtx *fasthttp.RequestCtx) (val string)
- func IsValidCookieDomain(domain string) bool
- func Random(n int) []byte
- func RandomString(n int) string
- func ReleaseCookie(cookie *http.Cookie)
- func RemoveCookie(name string, res http.ResponseWriter, req *http.Request)
- func RemoveFasthttpCookie(name string, reqCtx *fasthttp.RequestCtx)
- func Serialize(m interface{}) (string, error)
- func Set(setters ...OptionSetter)
- func UseDatabase(db Database)
- type Config
- type Database
- type OptionSet
- type OptionSetter
- type Provider
- func (p *Provider) Destroy(sid string)
- func (p *Provider) GC(duration time.Duration)
- func (p *Provider) Init(sid string, expires time.Duration) Session
- func (p *Provider) NewSession(sid string, expires time.Duration) Session
- func (p *Provider) Read(sid string, expires time.Duration) Session
- func (p *Provider) RegisterDatabase(db Database)
- type Session
- type Sessions
Constants ¶
const ( // DefaultCookieName the secret cookie's name for sessions DefaultCookieName = "gosessionsid" // DefaultGcDuration is the default Session Manager's GCDuration , which is 2 hours DefaultGcDuration = time.Duration(2) * time.Hour // DefaultCookieExpires is the default Session Manager's Cookie expire , which is 2 hours DefaultCookieExpires = DefaultGcDuration // DefaultCookieLength is the default Session Manager's CookieLength, which is 32 DefaultCookieLength = 32 )
const (
// Version current version number
Version = "0.0.6"
)
Variables ¶
Functions ¶
func AcquireCookie ¶
AcquireCookie returns an empty Cookie object from the pool.
The returned object may be returned back to the pool with ReleaseCookie. This allows reducing GC load.
func AddCookie ¶
func AddCookie(cookie *http.Cookie, res http.ResponseWriter)
AddCookie adds a cookie
func AddFasthttpCookie ¶
func AddFasthttpCookie(c *fasthttp.Cookie, reqCtx *fasthttp.RequestCtx)
AddFasthttpCookie adds a cookie to the client
func Deserialize ¶
Deserialize accepts an encoded string and a data struct which will be filled with the desierialized string using gob decoder
func Destroy ¶
func Destroy(res http.ResponseWriter, req *http.Request)
Destroy kills the net/http session and remove the associated cookie
func DestroyFasthttp ¶
func DestroyFasthttp(reqCtx *fasthttp.RequestCtx)
DestroyFasthttp kills the valyala/fasthttp session and remove the associated cookie
func GC ¶
func GC()
GC tick-tock for the store cleanup, call it manually if you set the AutoStart configuration field to false. otherwise do not call it manually. it's running inside a new goroutine
func GenerateSessionID ¶
GenerateSessionID returns a random string, used to set the session id
func GetCookie ¶
GetCookie returns cookie's value by it's name returns empty string if nothing was found
func GetFasthttpCookie ¶
func GetFasthttpCookie(name string, reqCtx *fasthttp.RequestCtx) (val string)
GetFasthttpCookie returns cookie's value by it's name returns empty string if nothing was found
func IsValidCookieDomain ¶
IsValidCookieDomain returns true if the receiver is a valid domain to set valid means that is recognised as 'domain' by the browser, so it(the cookie) can be shared with subdomains also
func Random ¶
Random takes a parameter (int) and returns random slice of byte ex: var randomstrbytes []byte; randomstrbytes = Random(32) note: this code doesn't belongs to me, but it works just fine*
func RandomString ¶
RandomString accepts a number(10 for example) and returns a random string using simple but fairly safe random algorithm
func ReleaseCookie ¶
ReleaseCookie returns the Cookie object acquired with AcquireCookie back to the pool.
Do not access released Cookie object, otherwise data races may occur.
func RemoveCookie ¶
func RemoveCookie(name string, res http.ResponseWriter, req *http.Request)
RemoveCookie deletes a cookie by it's name/key
func RemoveFasthttpCookie ¶
func RemoveFasthttpCookie(name string, reqCtx *fasthttp.RequestCtx)
RemoveFasthttpCookie deletes a cookie by it's name/key
func Serialize ¶
Serialize serialize any type to gob bytes and after returns its the base64 encoded string
func UseDatabase ¶
func UseDatabase(db Database)
UseDatabase adds a session database to the manager's provider, a session db doesn't have write access
Types ¶
type Config ¶
type Config struct { // Cookie string, the session's client cookie name, for example: "mysessionid" // // Defaults to "gosessionid" Cookie string // DecodeCookie set it to true to decode the cookie key with base64 URLEncoding // // Defaults to false DecodeCookie bool // Expires the duration of which the cookie must expires (created_time.Add(Expires)). // If you want to delete the cookie when the browser closes, set it to -1 but in this case, the server side's session duration is up to GcDuration // // Defaults to infinitive/unlimited life duration(0) Expires time.Duration // CookieLength the length of the sessionid's cookie's value, let it to 0 if you don't want to change it // // Defaults to 32 CookieLength int // GcDuration every how much duration(GcDuration) the memory should be clear for unused cookies (GcDuration) // for example: time.Duration(2)*time.Hour. it will check every 2 hours if cookie hasn't be used for 2 hours, // deletes it from backend memory until the user comes back, then the session continue to work as it was // // Defaults to 2 hours GcDuration time.Duration // DisableSubdomainPersistence set it to true in order dissallow your q subdomains to have access to the session cookie // // Defaults to false DisableSubdomainPersistence bool // DisableAutoGC disables the auto-gc running when the session manager is created // set to false to disable this behavior, you can call(onnce) manually the GC using the .GC function // // Defaults to false DisableAutoGC bool }
Config the configuration for sessions has 7 fields first is the cookieName, the session's name (string) ["mysessionsecretcookieid"] second enable if you want to decode the cookie's key also third is the time which the client's cookie expires forth is the cookie length (sessionid) int, defaults to 32, do not change if you don't have any reason to do fifth is the gcDuration (time.Duration) when this time passes it removes the unused sessions from the memory until the user come back sixth is the DisableSubdomainPersistence which you can set it to true in order dissallow your q subdomains to have access to the session cook seventh is the AutoStart which defaults to true, disable it in order to disable the autostart- GC when the session manager is created
type Database ¶
type Database interface { Load(string) map[string]interface{} Update(string, map[string]interface{}) }
Database is the interface which all session databases should implement By design it doesn't support any type of cookie session like other frameworks, I want to protect you, believe me, no context access (although we could) The scope of the database is to session somewhere the sessions in order to keep them after restarting the server, nothing more. the values are sessiond by the underline session, the check for new sessions, or 'this session value should added' are made automatically by q, you are able just to set the values to your backend database with Load function. session database doesn't have any write or read access to the session, the loading of the initial data is done by the Load(string) map[string]interfface{} function synchronization are made automatically, you can register more than one session database but the first non-empty Load return data will be used as the session values.
type OptionSet ¶
type OptionSet func(c *Config)
OptionSet implements the OptionSetter
func Cookie ¶
Cookie string, the session's client cookie name, for example: "mysessionid"
Defaults to "gosessionid"
func CookieLength ¶
CookieLength the length of the sessionid's cookie's value, let it to 0 if you don't want to change it
Defaults to 32
func DecodeCookie ¶
DecodeCookie set it to true to decode the cookie key with base64 URLEncoding
Defaults to false
func DisableAutoGC ¶
DisableAutoGC disables the auto-gc running when the session manager is created set to false to disable this behavior, you can call(onnce) manually the GC using the .GC function
Defaults to false
func DisableSubdomainPersistence ¶
DisableSubdomainPersistence set it to true in order dissallow your q subdomains to have access to the session cookie
Defaults to false
func Expires ¶
Expires the duration of which the cookie must expires (created_time.Add(Expires)). If you want to delete the cookie when the browser closes, set it to -1 but in this case, the server side's session duration is up to GcDuration
Defaults to infinitive/unlimited life duration(0)
func GcDuration ¶
GcDuration every how much duration(GcDuration) the memory should be clear for unused cookies (GcDuration) for example: time.Duration(2)*time.Hour. it will check every 2 hours if cookie hasn't be used for 2 hours, deletes it from backend memory until the user comes back, then the session continue to work as it was
Defaults to 2 hours
type OptionSetter ¶
type OptionSetter interface { // Set receives a pointer to the Config type and does the job of filling it Set(c *Config) }
OptionSetter used as the type of return of a func which sets a configuration field's value
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider contains the sessions memory store and any external databases
func (*Provider) Destroy ¶
Destroy destroys the session, removes all sessions values, the session itself and updates the registered session databases, this called from sessionManager which removes the client's cookie also.
func (*Provider) NewSession ¶
NewSession returns a new session from sessionid
func (*Provider) RegisterDatabase ¶
RegisterDatabase adds a session database a session db doesn't have write access
type Session ¶
type Session interface { ID() string Get(string) interface{} GetString(key string) string GetInt(key string) (int, error) GetInt64(key string) (int64, error) GetFloat32(key string) (float32, error) GetFloat64(key string) (float64, error) GetBoolean(key string) (bool, error) GetAll() map[string]interface{} VisitAll(cb func(k string, v interface{})) Set(string, interface{}) Delete(string) Clear() }
Session is session's session interface, think it like a local store of each session's values implemented by the internal session iteral, normally the end-user will never use this interface. gettable by the provider -> sessions -> your app
func Start ¶
func Start(res http.ResponseWriter, req *http.Request) Session
Start starts the session for the particular net/http request
func StartFasthttp ¶
func StartFasthttp(reqCtx *fasthttp.RequestCtx) Session
StartFasthttp starts the session for the particular valyala/fasthttp request
type Sessions ¶
type Sessions interface { // Set options/configuration fields in runtime Set(...OptionSetter) // UseDatabase ,optionally, adds a session database to the manager's provider, // a session db doesn't have write access // see https://github.com/kataras/go-sessions/tree/master/sessiondb UseDatabase(Database) // GC tick-tock for the store cleanup, call it manually if you set the AutoStart configuration field to false. // otherwise do not call it manually. // it's running inside a new goroutine GC() // Start starts the session for the particular net/http request Start(http.ResponseWriter, *http.Request) Session // Destroy kills the net/http session and remove the associated cookie Destroy(http.ResponseWriter, *http.Request) // StartFasthttp starts the session for the particular valyala/fasthttp request StartFasthttp(*fasthttp.RequestCtx) Session // DestroyFasthttp kills the valyala/fasthttp session and remove the associated cookie DestroyFasthttp(*fasthttp.RequestCtx) }
Sessions is the start point of this package contains all the registered sessions and manages them
func New ¶
func New(setters ...OptionSetter) Sessions
New creates & returns a new Sessions(manager) and start its GC (calls the .Init)