session

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2014 License: Apache-2.0 Imports: 26 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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeGob

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

func EncodeGob

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

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
}

Cookie session provider

func (*CookieProvider) SessionAll

func (pder *CookieProvider) SessionAll() int

Implement method, return 0.

func (*CookieProvider) SessionDestroy

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

Implement method, no used.

func (*CookieProvider) SessionExist

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

Cookie session is always existed

func (*CookieProvider) SessionGC

func (pder *CookieProvider) SessionGC()

Implement method, no used.

func (*CookieProvider) SessionInit

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

Init cookie session provider with max lifetime and config json. maxlifetime is ignored. json config:

securityKey - hash string
blockKey - gob encode hash string. it's saved as aes crypto.
securityName - recognized name in encoded cookie string
cookieName - cookie name
maxage - cookie max life time.

func (*CookieProvider) SessionRead

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

Get SessionStore in cooke. decode cooke string to map and put into SessionStore with sid.

func (*CookieProvider) SessionRegenerate

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

Implement method, no used.

func (*CookieProvider) SessionUpdate

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

Implement method, no used.

type CookieSessionStore

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

Cookie SessionStore

func (*CookieSessionStore) Delete

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

Delete value in cookie session

func (*CookieSessionStore) Flush

func (st *CookieSessionStore) Flush() error

Clean all values in cookie session

func (*CookieSessionStore) Get

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

Get value from cookie session

func (*CookieSessionStore) SessionID

func (st *CookieSessionStore) SessionID() string

Return id of this cookie session

func (*CookieSessionStore) SessionRelease

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

Write cookie session to http response cookie

func (*CookieSessionStore) Set

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

Set value to cookie session. the value are encoded as gob with hash block string.

type FileProvider

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

File session provider

func (*FileProvider) SessionAll

func (fp *FileProvider) SessionAll() int

Get active file session number. it walks save path to count files.

func (*FileProvider) SessionDestroy

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

Remove all files in this save path

func (*FileProvider) SessionExist

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

Check file session exist. it checkes the file named from sid exist or not.

func (*FileProvider) SessionGC

func (fp *FileProvider) SessionGC()

Recycle files in save path

func (*FileProvider) SessionInit

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

Init file session provider. savePath sets the session files path.

func (*FileProvider) SessionRead

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

Read file session by sid. if file is not exist, create it. the file path is generated from sid string.

func (*FileProvider) SessionRegenerate

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

Generate new sid for file session. it delete old file and create new file named from new sid.

type FileSessionStore

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

File session store

func (*FileSessionStore) Delete

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

Delete value in file session by given key

func (*FileSessionStore) Flush

func (fs *FileSessionStore) Flush() error

Clean all values in file session

func (*FileSessionStore) Get

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

Get value from file session

func (*FileSessionStore) SessionID

func (fs *FileSessionStore) SessionID() string

Get file session store id

func (*FileSessionStore) SessionRelease

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

Write file session to local file with Gob string

func (*FileSessionStore) Set

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

Set value to file session

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)

Create new Manager with provider name and json config string. provider name: 1. cookie 2. file 3. memory 4. redis 5. mysql json config: 1. is https default false 2. hashfunc default sha1 3. hashkey default beegosessionkey 4. maxage default is none

func (*Manager) GC

func (manager *Manager) GC()

Start session gc process. it can do gc in times after gc lifetime.

func (*Manager) GetActiveSession

func (manager *Manager) GetActiveSession() int

Get all active sessions count number.

func (*Manager) GetSessionStore

func (manager *Manager) GetSessionStore(sid string) (sessions SessionStore, err error)

Get SessionStore by its id.

func (*Manager) SessionDestroy

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

Destroy session by its id in http request cookie.

func (*Manager) SessionRegenerateId

func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore)

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) (session SessionStore)

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

func (*Manager) SetHashFunc

func (manager *Manager) SetHashFunc(hasfunc, hashkey string)

Set hash function for generating session id.

func (*Manager) SetSecure

func (manager *Manager) SetSecure(secure bool)

Set cookie with https.

type MemProvider

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

func (*MemProvider) SessionAll

func (pder *MemProvider) SessionAll() int

get count number of memory session

func (*MemProvider) SessionDestroy

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

delete session store in memory session by id

func (*MemProvider) SessionExist

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

check session store exist in memory session by sid

func (*MemProvider) SessionGC

func (pder *MemProvider) SessionGC()

clean expired session stores in memory session

func (*MemProvider) SessionInit

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

init memory session

func (*MemProvider) SessionRead

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

get memory session store by sid

func (*MemProvider) SessionRegenerate

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

generate new sid for session store in memory session

func (*MemProvider) SessionUpdate

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

expand time of session store by id in memory session

type MemSessionStore

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

memory session store. it saved sessions in a map in memory.

func (*MemSessionStore) Delete

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

delete in memory session by key

func (*MemSessionStore) Flush

func (st *MemSessionStore) Flush() error

clear all values in memory session

func (*MemSessionStore) Get

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

get value from memory session by key

func (*MemSessionStore) SessionID

func (st *MemSessionStore) SessionID() string

get this id of memory session store

func (*MemSessionStore) SessionRelease

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

Implement method, no used.

func (*MemSessionStore) Set

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

set value to memory session

type Provider

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()
}

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

type SessionStore

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
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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