session

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 3, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

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/astaxie/beego/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/astaxie/beego/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
	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/

Documentation

Overview

Package session provider

Usage: import(

"github.com/astaxie/beego/session"

)

	func init() {
     globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`)
		go globalSessions.GC()
	}

more docs: http://beego.me/docs/module/session.md

Index

Constants

This section is empty.

Variables

View Source
var CookieName string

SLogger a helpful variable to log information about session

Functions

func DecodeGob

func DecodeGob(encoded []byte) (map[interface{}]interface{}, error)

DecodeGob decodes gob data to a map.

func EncodeGob

func EncodeGob(obj map[interface{}]interface{}) ([]byte, error)

EncodeGob encodes the object map to gob format.

func RandomCreateBytes

func RandomCreateBytes(n int, alphabets ...byte) []byte

RandomCreateBytes generates random []byte of length n using the specified alphabet.

func Register

func Register(name string, provide Provider)

Register makes a session provide available by the provided name. If Register is called twice with the same name or if driver is nil, it panics.

Types

type CookieProvider

type CookieProvider struct {
	// contains filtered or unexported fields
}

CookieProvider provides cookie-based session storage.

func (*CookieProvider) SessionAll

func (pder *CookieProvider) SessionAll() int

SessionAll implements the Provider interface; returns 0 for cookie.

func (*CookieProvider) SessionDestroy

func (pder *CookieProvider) SessionDestroy(sid string) error

SessionDestroy implements the Provider interface; no-op for cookie.

func (*CookieProvider) SessionExist

func (pder *CookieProvider) SessionExist(sid string) bool

SessionExist returns true; cookie session is always considered to exist.

func (*CookieProvider) SessionGC

func (pder *CookieProvider) SessionGC()

SessionGC implements the Provider interface; no-op for cookie.

func (*CookieProvider) SessionInit

func (pder *CookieProvider) SessionInit(maxlifetime int64, config string) error

SessionInit initializes the cookie session provider. maxlifetime is ignored. JSON config: securityKey (hash string), blockKey (AES key for gob encoding), securityName (name in encoded cookie), cookieName, maxage (cookie max lifetime).

func (*CookieProvider) SessionRead

func (pder *CookieProvider) SessionRead(sid string) (Store, error)

SessionRead decodes the cookie string to a map and returns a SessionStore with the given sid.

func (*CookieProvider) SessionRegenerate

func (pder *CookieProvider) SessionRegenerate(oldsid, sid string) (Store, error)

SessionRegenerate implements the Provider interface; no-op for cookie.

func (*CookieProvider) SessionUpdate

func (pder *CookieProvider) SessionUpdate(sid string) error

SessionUpdate implements the Provider interface; no-op for cookie.

type CookieSessionStore

type CookieSessionStore struct {
	// contains filtered or unexported fields
}

CookieSessionStore stores session data in cookies.

func (*CookieSessionStore) Delete

func (st *CookieSessionStore) Delete(key interface{})

Delete removes a value from the cookie session.

func (*CookieSessionStore) Flush

func (st *CookieSessionStore) Flush()

Flush clears all values in the cookie session.

func (*CookieSessionStore) Get

func (st *CookieSessionStore) Get(key interface{}) option.Option[interface{}]

Get retrieves a value from the cookie session.

func (*CookieSessionStore) SessionID

func (st *CookieSessionStore) SessionID() string

SessionID returns the id of this cookie session.

func (*CookieSessionStore) SessionRelease

func (st *CookieSessionStore) SessionRelease(w http.ResponseWriter)

SessionRelease writes the cookie session to the HTTP response.

func (*CookieSessionStore) Set

func (st *CookieSessionStore) Set(key, value interface{})

Set stores a value in the cookie session (encoded as gob with hash).

type FileProvider

type FileProvider struct {
	// contains filtered or unexported fields
}

FileProvider provides file-based session storage.

func (*FileProvider) SessionAll

func (fp *FileProvider) SessionAll() int

SessionAll returns the count of active file sessions by walking the save path.

func (*FileProvider) SessionDestroy

func (fp *FileProvider) SessionDestroy(sid string) error

SessionDestroy removes the session file for the given sid.

func (*FileProvider) SessionExist

func (fp *FileProvider) SessionExist(sid string) bool

SessionExist checks whether the file session exists (file named by sid).

func (*FileProvider) SessionGC

func (fp *FileProvider) SessionGC()

SessionGC removes expired session files from the save path.

func (*FileProvider) SessionInit

func (fp *FileProvider) SessionInit(maxlifetime int64, savePath string) error

SessionInit initializes the file session provider. savePath sets the directory for session files.

func (*FileProvider) SessionRead

func (fp *FileProvider) SessionRead(sid string) (Store, error)

SessionRead reads the file session by sid, creating the file if it does not exist.

func (*FileProvider) SessionRegenerate

func (fp *FileProvider) SessionRegenerate(oldsid, sid string) (Store, error)

SessionRegenerate creates a new session file for the new sid and copies data from the old one.

type FileSessionStore

type FileSessionStore struct {
	// contains filtered or unexported fields
}

FileSessionStore stores session data in files.

func (*FileSessionStore) Delete

func (fs *FileSessionStore) Delete(key interface{})

Delete removes a value from the file session by key.

func (*FileSessionStore) Flush

func (fs *FileSessionStore) Flush()

Flush clears all values in the file session.

func (*FileSessionStore) Get

func (fs *FileSessionStore) Get(key interface{}) option.Option[interface{}]

Get retrieves a value from the file session.

func (*FileSessionStore) SessionID

func (fs *FileSessionStore) SessionID() string

SessionID returns the file session store id.

func (*FileSessionStore) SessionRelease

func (fs *FileSessionStore) SessionRelease(w http.ResponseWriter)

SessionRelease writes the file session to local storage using Gob encoding.

func (*FileSessionStore) Set

func (fs *FileSessionStore) Set(key, value interface{})

Set stores a value in the file session.

type Log

type Log struct {
	*log.Logger
}

Log implements the log.Logger interface for session logging.

func NewSessionLog

func NewSessionLog(out io.Writer) *Log

NewSessionLog creates a Logger for session using the given io.Writer.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager contains Provider and its configuration.

func NewManager

func NewManager(provideName, config string) (*Manager, error)

NewManager creates a new Manager with provider name and JSON config string. Supported providers: cookie, file, memory, redis, mysql. JSON config: is https (default false), hashfunc (default sha1), hashkey (default beegosessionkey), maxage (default none).

func (*Manager) GC

func (manager *Manager) GC()

GC starts the session garbage collection process, scheduled at gc lifetime intervals.

func (*Manager) GetActiveSession

func (manager *Manager) GetActiveSession() int

GetActiveSession Get all active sessions count number.

func (*Manager) GetSessionStore

func (manager *Manager) GetSessionStore(sid string) result.Result[Store]

GetSessionStore Get SessionStore by its id.

func (*Manager) SessionDestroy

func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request) result.VoidResult

SessionDestroy Destroy session by its id in http request cookie.

func (*Manager) SessionRegenerateID

func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) result.Result[Store]

SessionRegenerateID Regenerate a session id for this SessionStore who's id is saving in http request.

func (*Manager) SessionStart

func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) result.Result[Store]

SessionStart generate or read the session id from http request. if session id exists, return SessionStore with this id.

func (*Manager) SetSecure

func (manager *Manager) SetSecure(secure bool)

SetSecure sets whether the cookie should be sent over HTTPS only.

type MemProvider

type MemProvider struct {
	// contains filtered or unexported fields
}

MemProvider implements the Provider interface for in-memory sessions.

func (*MemProvider) SessionAll

func (pder *MemProvider) SessionAll() int

SessionAll returns the count of active memory sessions.

func (*MemProvider) SessionDestroy

func (pder *MemProvider) SessionDestroy(sid string) error

SessionDestroy removes the session store from memory by id.

func (*MemProvider) SessionExist

func (pder *MemProvider) SessionExist(sid string) bool

SessionExist checks whether the session exists in memory by sid.

func (*MemProvider) SessionGC

func (pder *MemProvider) SessionGC()

SessionGC removes expired session stores from memory.

func (*MemProvider) SessionInit

func (pder *MemProvider) SessionInit(maxlifetime int64, savePath string) error

SessionInit initializes the memory session provider.

func (*MemProvider) SessionRead

func (pder *MemProvider) SessionRead(sid string) (Store, error)

SessionRead returns the memory session store for the given sid.

func (*MemProvider) SessionRegenerate

func (pder *MemProvider) SessionRegenerate(oldsid, sid string) (Store, error)

SessionRegenerate creates a new session store with the new sid, copying data from the old one.

func (*MemProvider) SessionUpdate

func (pder *MemProvider) SessionUpdate(sid string) error

SessionUpdate updates the access time for the session store by id.

type MemSessionStore

type MemSessionStore struct {
	// contains filtered or unexported fields
}

MemSessionStore stores session data in memory.

func (*MemSessionStore) Delete

func (st *MemSessionStore) Delete(key interface{})

Delete removes a value from the memory session by key.

func (*MemSessionStore) Flush

func (st *MemSessionStore) Flush()

Flush clears all values in the memory session.

func (*MemSessionStore) Get

func (st *MemSessionStore) Get(key interface{}) option.Option[interface{}]

Get retrieves a value from the memory session by key.

func (*MemSessionStore) SessionID

func (st *MemSessionStore) SessionID() string

SessionID returns the session store ID.

func (*MemSessionStore) SessionRelease

func (st *MemSessionStore) SessionRelease(w http.ResponseWriter)

SessionRelease implements the Store interface; no-op for memory.

func (*MemSessionStore) Set

func (st *MemSessionStore) Set(key, value interface{})

Set stores a value in the memory session.

type Provider

type Provider interface {
	SessionInit(gclifetime int64, config string) error
	SessionRead(sid string) (Store, error)
	SessionExist(sid string) bool
	SessionRegenerate(oldsid, sid string) (Store, error)
	SessionDestroy(sid string) error
	SessionAll() int // return count of active sessions
	SessionGC()
}

Provider contains global session methods and saved SessionStores. it can operate a SessionStore by its id.

type Store

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

Store contains all data for one session process with specific id.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL