package
2.0.4
Repository: https://github.com/cpusoft/beego.git
Documentation: pkg.go.dev

# README

session

session is a Go session manager. It can use many session providers. Just like the database/sql and database/sql/driver.

How to install?

go get github.com/beego/beego/v2/server/web/session

What providers are supported?

As of now this session manager support memory, file, Redis and MySQL.

How to use it?

First you must import it

import (
	"github.com/beego/beego/v2/server/web/session"
)

Then in you web app init the global session manager

var globalSessions *session.Manager
  • Use memory as provider:

    func init() { globalSessions, _ = session.NewManager("memory", {"cookieName":"gosessionid","gclifetime":3600}) go globalSessions.GC() }

  • Use file as provider, the last param is the path where you want file to be stored:

    func init() { globalSessions, _ = session.NewManager("file",{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"./tmp"}) go globalSessions.GC() }

  • Use Redis as provider, the last param is the Redis conn address,poolsize,password:

    func init() { globalSessions, _ = session.NewManager("redis", {"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:6379,100,astaxie"}) go globalSessions.GC() }

  • Use MySQL as provider, the last param is the DSN, learn more from mysql:

    func init() { globalSessions, _ = session.NewManager( "mysql", {"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"username:password@protocol(address)/dbname?param=value"}) go globalSessions.GC() }

  • Use Cookie as provider:

    func init() { globalSessions, _ = session.NewManager( "cookie", {"cookieName":"gosessionid","enableSetCookie":false,"gclifetime":3600,"ProviderConfig":"{\"cookieName\":\"gosessionid\",\"securityKey\":\"beegocookiehashkey\"}"}) go globalSessions.GC() }

Finally in the handlerfunc you can use it like this

func login(w http.ResponseWriter, r *http.Request) {
	sess := globalSessions.SessionStart(w, r)
	defer sess.SessionRelease(w)
	username := sess.Get("username")
	fmt.Println(username)
	if r.Method == "GET" {
		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, nil)
	} else {
		fmt.Println("username:", r.Form["username"])
		sess.Set("username", r.Form["username"])
		fmt.Println("password:", r.Form["password"])
	}
}

How to write own provider?

When you develop a web app, maybe you want to write own provider because you must meet the requirements.

Writing a provider is easy. You only need to define two struct types (Session and Provider), which satisfy the interface definition. Maybe you will find the memory provider is a good example.

type SessionStore interface {
	Set(key, value interface{}) error     //set session value
	Get(key interface{}) interface{}      //get session value
	Delete(key interface{}) error         //delete session value
	SessionID() string                    //back current sessionID
	SessionRelease(w http.ResponseWriter) // release the resource & save data to provider & return the data
	Flush() error                         //delete all data
}

type Provider interface {
	SessionInit(gclifetime int64, config string) error
	SessionRead(sid string) (SessionStore, error)
	SessionExist(sid string) (bool, error)
	SessionRegenerate(oldsid, sid string) (SessionStore, error)
	SessionDestroy(sid string) error
	SessionAll() int //get all active session
	SessionGC()
}

LICENSE

BSD License http://creativecommons.org/licenses/BSD/

# Packages

Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/beego/beego/v2/server/web/session/couchbase" "github.com/beego/beego/v2/server/web/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}``) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md.
Package ledis provide session Provider.
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/beego/beego/v2/server/web/session/memcache" "github.com/beego/beego/v2/server/web/session" ) func init() { globalSessions, _ = session.NewManager("memcache", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}``) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md.
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/beego/beego/v2/server/web/session/mysql" "github.com/beego/beego/v2/server/web/session" ) func init() { globalSessions, _ = session.NewManager("mysql", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}``) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md.
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/beego/beego/v2/server/web/session/postgresql" "github.com/beego/beego/v2/server/web/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}``) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md.
Package redis for session provider depend on github.com/gomodule/redigo/redis go install github.com/gomodule/redigo/redis Usage: import( _ "github.com/beego/beego/v2/server/web/session/redis" "github.com/beego/beego/v2/server/web/session" ) func init() { globalSessions, _ = session.NewManager("redis", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}``) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md.
Package redis for session provider depend on github.com/go-redis/redis go install github.com/go-redis/redis Usage: import( _ "github.com/beego/beego/v2/server/web/session/redis_cluster" "github.com/beego/beego/v2/server/web/session" ) func init() { globalSessions, _ = session.NewManager("redis_cluster", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070;127.0.0.1:7071"}``) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md.
Package redis for session provider depend on github.com/go-redis/redis go install github.com/go-redis/redis Usage: import( _ "github.com/beego/beego/v2/server/web/session/redis_sentinel" "github.com/beego/beego/v2/server/web/session" ) func init() { globalSessions, _ = session.NewManager("redis_sentinel", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:26379;127.0.0.2:26379"}``) go globalSessions.GC() } more detail about params: please check the notes on the function SessionInit in this package.
No description provided by the author

# Functions

CfgGcLifeTime set session lift time.
CfgCookieName set key of session id.
CfgDomain set cookie domain.
EnableSidInURLQuery enable session id in query string.
CfgGcLifeTime set session gc lift time.
DisableHTTPOnly set HTTPOnly for http.Cookie.
CfgMaxLifeTime set session lift time.
CfgProviderConfig configure session provider.
CfgSameSite set http.SameSite.
CfgSecure set Secure for http.Cookie.
CfgSessionIdInHTTPHeader enable session id in http header.
CfgCookieName set len of session id.
CfgSessionIdPrefix set prefix of session id.
CfgSetCookie whether set `Set-Cookie` header in HTTP response.
CfgSetSessionNameInHTTPHeader set key of session id in http header.
DecodeGob decode data to map.
EncodeGob encode the obj to gob.
GetProvider.
NewManager Create new Manager with provider name and json config string.
No description provided by the author
NewSessionLog set io.Writer to create a Logger for session.
Register makes a session provide available by the provided name.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Variables

SLogger a helpful variable to log information about session.

# Structs

CookieProvider Cookie session provider.
CookieSessionStore Cookie SessionStore.
FileProvider File session provider.
FileSessionStore File session store.
Log implement the log.Logger.
Manager contains Provider and its configuration.
ManagerConfig define the session config.
MemProvider Implement the provider interface.
MemSessionStore memory session store.

# Interfaces

Provider contains global session methods and saved SessionStores.
Store contains all data for one session process with specific id.

# Type aliases

No description provided by the author
No description provided by the author