session

package module
v0.0.0-...-e3ae77d Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2017 License: MIT Imports: 26 Imported by: 2

README

Session

The session package is a Macross session manager. It can use many session providers.

How to install?

go get github.com/macross-contrib/session

What providers are supported?

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

How to use it?

First you must import it

import (
	"github.com/macross-contrib/session"
)
  • Use memory as provider:

      session.Options{"memory", `{"cookieName":"MacrossSessionId","gcLifetime":3600}`}
    
  • Use file as provider, the last param is the path where you want file to be stored:

      session.Options{"file", `{"cookieName":"MacrossSessionId","gcLifetime":3600,"providerConfig":"./data/session"}`}
    
  • Use Redis as provider, the last param is the Redis conn address,poolsize,password:

      session.Options{"redis", `{"cookieName":"MacrossSessionId","gcLifetime":3600,"providerConfig":"127.0.0.1:6379,100,macross"}`}
    
  • Use Cookie as provider:

      session.Options{"cookie", `{"cookieName":"MacrossSessionId","enableSetCookie":false,"gcLifetime":3600,"providerConfig":"{\"cookieName\":\"MacrossSessionId\",\"securityKey\":\"Macrosscookiehashkey\"}"}`}
    

Finally in the code you can use it like this

package main

import (
	"github.com/insionng/macross"
	"github.com/insionng/macross/recover"
	"github.com/macross-contrib/session"
	//_ "github.com/macross-contrib/session/redis"
	"log"
)

func main() {

	v := macross.New()
	v.Use(recover.Recover())
	v.Use(session.Sessioner(session.Options{"file", `{"cookieName":"MacrossSessionId","gcLifetime":3600,"providerConfig":"./data/session"}`}))
	//v.Use(session.Sessioner(session.Options{"redis", `{"cookieName":"MacrossSessionId","gcLifetime":3600,"providerConfig":"127.0.0.1:6379"}`}))

	v.Get("/get", func(self *macross.Context) error {
		value := "nil"
		valueIf := self.Session.Get("key")
		if valueIf != nil {
			value = valueIf.(string)
		}

		return self.String(value)

	})

	v.Get("/set", func(self *macross.Context) error {

		val := self.QueryParam("v")
		if len(val) == 0 {
			val = "value"
		}

		err := self.Session.Set("key", val)
		if err != nil {
			log.Printf("sess.set %v \n", err)
		}
		return self.String("ok")
	})

	v.Listen(":9000")
}

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
	ID() string                    //back current sessionID
	Release(ctx *macross.Context) error // release the resource & save data to provider & return the data
	Flush() error                         //delete all data
}

type Provider interface {
	Init(gcLifetime int64, config string) error
	Read(sid string) (macross.RawStore, error)
	Exist(sid string) bool
	Regenerate(oldsid, sid string) (macross.RawStore, error)
	Destroy(sid string) error
	Count() int //get all active session
	GC()
}

LICENSE

MIT License

Documentation

Index

Constants

View Source
const (
	CONTEXT_SESSION_KEY = "_SESSION_STORE"
	COOKIE_FLASH_KEY    = "_COOKIE_FLASH"
	CONTEXT_FLASH_KEY   = "Flash"
	SESSION_FLASH_KEY   = "_SESSION_FLASH"
	SESSION_INPUT_KEY   = "_SESSION_INPUT"
)

Variables

This section is empty.

Functions

func CleanInput

func CleanInput(c *macross.Context)

func DecodeGob

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

DecodeGob decode data to map

func EncodeGob

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

EncodeGob encode the obj to gob

func FlashValue

func FlashValue(c *macross.Context) macross.Flash

func GetFlash

func GetFlash(c *macross.Context) *macross.Flash

func GetInput

func GetInput(c *macross.Context) url.Values

func NewFlash

func NewFlash(ctx *macross.Context) *macross.Flash

func RandomCreateBytes

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

RandomCreateBytes generate random []byte by specify chars.

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.

func SaveInput

func SaveInput(c *macross.Context)

func Sessioner

func Sessioner(op ...Options) macross.Handler

Sessioner Macross session 中间件

Types

type CookieProvider

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

CookieProvider Cookie session provider

func (*CookieProvider) Count

func (pder *CookieProvider) Count() int

SessionCount Implement method, return 0.

func (*CookieProvider) Destory

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

Destory Implement method, no used.

func (*CookieProvider) Exist

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

Exist Cookie session is always existed

func (*CookieProvider) GC

func (pder *CookieProvider) GC()

GC Implement method, no used.

func (*CookieProvider) Init

func (pder *CookieProvider) Init(maxLifetime int64, config string) error

Init 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) Read

func (pder *CookieProvider) Read(sid string) (macross.RawStore, error)

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

func (*CookieProvider) Regenerate

func (pder *CookieProvider) Regenerate(oldsid, sid string) (macross.RawStore, error)

Regenerate Implement method, no used.

func (*CookieProvider) SessionUpdate

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

SessionUpdate Implement method, no used.

type CookieSessionStore

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

CookieSessionStore 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

Flush Clean all values in cookie session

func (*CookieSessionStore) Get

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

Get value from cookie session

func (*CookieSessionStore) ID

func (st *CookieSessionStore) ID() string

SessionID Return id of this cookie session

func (*CookieSessionStore) Release

func (st *CookieSessionStore) Release(ctx *macross.Context) error

SessionRelease 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
}

FileProvider File session provider

func (*FileProvider) Count

func (fp *FileProvider) Count() int

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

func (*FileProvider) Destory

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

Destory Remove all files in this save path

func (*FileProvider) Exist

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

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

func (*FileProvider) GC

func (fp *FileProvider) GC()

GC Recycle files in save path

func (*FileProvider) Init

func (fp *FileProvider) Init(maxLifetime int64, savePath string) error

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

func (*FileProvider) Read

func (fp *FileProvider) Read(sid string) (macross.RawStore, error)

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

func (*FileProvider) Regenerate

func (fp *FileProvider) Regenerate(oldsid, sid string) (macross.RawStore, error)

Regenerate 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
}

FileSessionStore 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

Flush Clean all values in file session

func (*FileSessionStore) Get

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

Get value from file session

func (*FileSessionStore) ID

func (fs *FileSessionStore) ID() string

ID Get file session store id

func (*FileSessionStore) Release

func (fs *FileSessionStore) Release(ctx *macross.Context) (err error)

SessionRelease 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.

var GlobalManager *Manager

func NewManager

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

NewManager 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) Count

func (m *Manager) Count() int

Count counts and returns number of sessions.

func (*Manager) Destory

func (m *Manager) Destory(self *macross.Context) error

Destory deletes a session by given ID.

func (*Manager) GC

func (manager *Manager) GC()

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

func (*Manager) Read

func (manager *Manager) Read(sid string) (rawStore macross.RawStore, err error)

Read returns raw session store by session ID.

func (*Manager) RegenerateId

func (manager *Manager) RegenerateId(ctx *macross.Context) (session macross.RawStore, err error)

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

func (*Manager) SetSecure

func (manager *Manager) SetSecure(secure bool)

SetSecure Set cookie with https.

func (*Manager) Start

func (manager *Manager) Start(ctx *macross.Context) (session macross.RawStore, err error)

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

type MemProvider

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

MemProvider Implement the provider interface

func (*MemProvider) Count

func (pder *MemProvider) Count() int

Count get count number of memory session

func (*MemProvider) Destory

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

Destory delete session store in memory session by id

func (*MemProvider) Exist

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

Exist check session store exist in memory session by sid

func (*MemProvider) GC

func (pder *MemProvider) GC()

GC clean expired session stores in memory session

func (*MemProvider) Init

func (pder *MemProvider) Init(maxLifetime int64, savePath string) error

Init init memory session

func (*MemProvider) Read

func (pder *MemProvider) Read(sid string) (macross.RawStore, error)

Read get memory session store by sid

func (*MemProvider) Regenerate

func (pder *MemProvider) Regenerate(oldsid, sid string) (macross.RawStore, error)

Regenerate generate new sid for session store in memory session

func (*MemProvider) SessionUpdate

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

SessionUpdate expand time of session store by id in memory session

type MemSessionStore

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

MemSessionStore 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

Flush 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) ID

func (st *MemSessionStore) ID() string

SessionID get this id of memory session store

func (*MemSessionStore) Release

func (st *MemSessionStore) Release(ctx *macross.Context) error

SessionRelease Implement method, no used.

func (*MemSessionStore) Set

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

Set value to memory session

type Options

type Options struct {
	Provider string
	Config   string
}

type Provider

type Provider interface {
	Init(gcLifetime int64, config string) error
	Read(sid string) (macross.RawStore, error)
	Exist(sid string) bool
	Regenerate(oldsid, sid string) (macross.RawStore, error)
	Destory(sid string) error
	Count() int //get all active session
	GC()
}

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

type Store

type Store interface {
	macross.RawStore
	// Read returns raw session store by session ID.
	Read(string) (macross.RawStore, error)
	// Destory deletes a session.
	Destory(*macross.Context) error
	// RegenerateId regenerates a session store from old session ID to new one.
	RegenerateId(*macross.Context) (macross.RawStore, error)
	// Count counts and returns number of sessions.
	Count() int
	// GC calls GC to clean expired sessions.
	GC()
}

Store is the interface that contains all data for one session process with specific ID.

func GetStore

func GetStore(c *macross.Context) Store

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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