modulepackage
0.0.0-20160905201309-74f6ac73d5d5
Repository: https://github.com/fasthttp-contrib/sessions.git
Documentation: pkg.go.dev
# README
Fast, unique & cross-framework http sessions for Go.
Easy to learn, while providing robust set of features.
Ideally suited for both experienced and novice Developers.
Quick view
import "github.com/fasthttp-contrib/sessions"
sess := sessions.StartFasthttp(*fasthttp.RequestCtx)
sess.ID() string
sess.Get(string) interface{}
sess.GetString(key string) string
sess.GetInt(key string) int
sess.GetAll() map[string]interface{}
sess.VisitAll(cb func(k string, v interface{}))
sess.Set(string, interface{})
sess.Delete(string)
sess.Clear()
Installation
The only requirement is the Go Programming Language, at least v1.7.
$ go get -u github.com/fasthttp-contrib/sessions
Features
- Focus on simplicity and performance, it's the fastest sessions provider in Go world.
- Cleans the temp memory when a session is idle, and re-allocates it to the temp memory when it's necessary.
- The most used sessions are optimized to be in the front of the memory's list.
- Supports any type of external database.
- Works with both net/http and valyala/fasthttp.
Docs
Take a look at the ./examples.
OUTLINE
// 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)
// 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)
// UseDatabase ,optionally, adds a session database to the manager's provider,
// a session db doesn't have write access
// see https://github.com/kataras/go-sessions/tree/master/sessiondb
UseDatabase(Database)
// UpdateConfig updates the configuration field (Config does not receives a pointer, so this is a way to update a pre-defined configuration)
UpdateConfig(Config)
Usage FASTHTTP
StartFasthttp
returns again Session
, Session outline
type Session interface {
ID() string
Get(string) interface{}
GetString(key string) string
GetInt(key string) int
GetAll() map[string]interface{}
VisitAll(cb func(k string, v interface{}))
Set(string, interface{})
Delete(string)
Clear()
}
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:
// type Session interface {
// ID() string
// Get(string) interface{}
// GetString(key string) string
// GetInt(key string) int
// GetAll() map[string]interface{}
// VisitAll(cb func(k string, v interface{}))
// Set(string, interface{})
// Delete(string)
// Clear()
//}
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")
}
})
}
Usage NET/HTTP
Start
returns a Session
, Session outline
type Session interface {
ID() string
Get(string) interface{}
GetString(key string) string
GetInt(key string) int
GetAll() map[string]interface{}
VisitAll(cb func(k string, v interface{}))
Set(string, interface{})
Delete(string)
Clear()
}
package main
import (
"fmt"
"github.com/kataras/go-sessions"
"net/http"
)
func main() {
// set some values to the session
setHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
values := map[string]interface{}{
"Name": "go-sessions",
"Days": "1",
"Secret": "dsads£2132215£%%Ssdsa",
}
sess := sessions.Start(res, req) // init the session
// sessions.Start returns:
// type Session interface {
// ID() string
// Get(string) interface{}
// GetString(key string) string
// GetInt(key string) int
// GetAll() map[string]interface{}
// VisitAll(cb func(k string, v interface{}))
// Set(string, interface{})
// Delete(string)
// Clear()
//}
for k, v := range values {
sess.Set(k, v) // fill session, set each of the key-value pair
}
res.Write([]byte("Session saved, go to /get to view the results"))
})
http.Handle("/set/", setHandler)
// get the values from the session
getHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
sess := sessions.Start(res, req) // init the session
sessValues := sess.GetAll() // get all values from this session
res.Write([]byte(fmt.Sprintf("%#v", sessValues)))
})
http.Handle("/get/", getHandler)
// clear all values from the session
clearHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
sess := sessions.Start(res, req)
sess.Clear()
})
http.Handle("/clear/", clearHandler)
// destroys the session, clears the values and removes the server-side entry and client-side sessionid cookie
destroyHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
sessions.Destroy(res, req)
})
http.Handle("/destroy/", destroyHandler)
fmt.Println("Open a browser tab and navigate to the localhost:8080/set/")
http.ListenAndServe(":8080", nil)
}
FAQ
If you'd like to discuss this package, or ask questions about it, feel free to
- Explore these questions.
- Post an issue or idea here.
- Navigate to the Chat.
Versioning
Current: v0.0.3
Read more about Semantic Versioning 2.0.0
- http://semver.org/
- https://en.wikipedia.org/wiki/Software_versioning
- https://wiki.debian.org/UpstreamGuide#Releases_and_Versions
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.
# Functions
AcquireCookie returns an empty Cookie object from the pool.
AddCookie adds a cookie.
AddFasthttpCookie adds a cookie to the client.
Deserialize accepts an encoded string and a data struct which will be filled with the desierialized string using gob decoder.
Destroy kills the net/http session and remove the associated cookie.
DestroyFasthttp kills the valyala/fasthttp session and remove the associated cookie.
GenerateSessionID returns a random string, used to set the session id.
GetCookie returns cookie's value by it's name returns empty string if nothing was found.
GetFasthttpCookie returns cookie's value by it's name returns empty string if nothing was found.
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.
New creates & returns a new Sessions(manager) and start its GC.
NewProvider returns a new sessions provider.
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*.
RandomString accepts a number(10 for example) and returns a random string using simple but fairly safe random algorithm.
ReleaseCookie returns the Cookie object acquired with AcquireCookie back to the pool.
RemoveCookie deletes a cookie by it's name/key.
RemoveFasthttpCookie deletes a cookie by it's name/key.
Serialize serialize any type to gob bytes and after returns its the base64 encoded string.
Start starts the session for the particular net/http request.
StartFasthttp starts the session for the particular valyala/fasthttp request.
UpdateConfig updates the sessions configuration.
UseDatabase adds a session database to the manager's provider, a session db doesn't have write access.
# Constants
DefaultCookieExpires is the default Session Manager's Cookie expire , which is 2 hours.
DefaultCookieLength is the default Session Manager's CookieLength, which is 32.
DefaultCookieName the secret cookie's name for sessions.
DefaultGcDuration is the default Session Manager's GCDuration , which is 2 hours.
Version current version number.
# Variables
CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie.
CookieExpireUnlimited indicates that the cookie doesn't expire.
# Structs
Config the configuration for sessions has 6 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
.
No description provided by the author
# Interfaces
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.
No description provided by the author
No description provided by the author