session

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2019 License: MIT, MIT, MIT Imports: 15 Imported by: 0

README

Session 会话组件

用于网页会话数据储存的组件

功能

  • 提供基于缓存或者客户端储存(cookie)机制的缓存驱动
  • 提供访问刷新会话生命周期的功能
  • 提供Cooke以及Header方式传递会话Token的功能
  • 提供符合 github.com/herb/user 接口的登录功能
  • 便于序列化的配置方式

配置说明

#TOML版本,其他版本可以根据对应格式配置

#基本设置
#驱动名,可选值如下
#DriverName="cookie"  基于的客户端会话
#DriverName="cache"  基于的缓存的服务器端会话
DriverName="cache"
#缓存内部使用的序列化器。默认值为msgpack,需要先行引入
Marshaler="msgpack"
#当使用自动模式安装中间件时使用的模式
#"header"使用header模式
#"cookie"或其他值使用cookie模式
Mode="cookie"
#Token设置
#基于小时的会话令牌有效时间
TokenLifetimeInHour=0
#基于天的会话令牌有效时间
#当基于小时的挥发令牌有效事件非0时,本选项无效
TokenLifetimeInDay =7
#基于天的令牌最大有效时间
#当UpdateActiveIntervalInSecond值大于0时,令牌在访问后会更新有效时间
#这个值决定了有效事件的最大值
TokenMaxLifetimeInDay=24
#访问时更新token的间隔。默认值为60
UpdateActiveIntervalInSecond=60
#会话令牌在HTTP请求上下文中的名字。当同时使用多套上下文时需要指定不同的名字。默认值为"token"
TokenContextName="token"
#是否自动生成会话,默认值为false
AutoGenerate=false


#Cooke设置
#储存session的cookie名,默认值为"herb-session"
CookieName="herb-session"
#Cookie的路径设置,默认值为"/"
CookiePath="/"
#Cookie的Secure,默认值为false
CookieSecure=false

#其他设置
#默认会话的标志位信息.默认值为1
DefaultSessionFlag=1


#客户端会话设置
#客户端会话密钥
ClientStoreKey="key"

#缓存会话设置
#会话令牌前缀模式。可用值为
#"empty":空
#"raw":原始值
#"md5":md5后的摘要值
#默认值为raw
TokenPrefixMode=""
#令牌数据长度。
#注意数据长度是原始数据长度。存入cookie时的长度还要经过base64转换
#默认值为64
TokenLength=64
#缓存驱动
"Cache.Driver"="syncmapcache"
#缓存有限时间
"Cache.TTL"=1800
#具体缓存配置
"Cache.Config.Size"=5000000

使用方法

创建会话,进行配置
store:=session.New()
config:=&session.StoreConfig{}
err=toml.Unmarshal(data,&config)
err=config.ApplyTo(store)
安装会话中间件

安装会话中间件的方式包括cookie模式,header模式,自动模式

1.cookie模式安装,自动通过配置中CookieName的cookie值作为session的token

app.Use(store.CookieMiddleware)

2.header模式安装,通过指定的请求头的值做为session token。

客户端需要自行维护token

app.Use(store.HeaderMiddleware("headername"))

3.自动模式安装。

通过配置文件中的Mode值决定使用cookie模式还是session模式安装

如果Mode值为header,使用配置中的CookieName为请求头作为session token值,由客户端自行维护token

其他情况下同cookie模式安装

app.Use(store.InstallMiddleware())

4.使用注销中间件

将对应请的session清除,一般用于注销

app.Use(store.DestoryMiddleware()).HandleFunc(logoutaction)
在动作中设置与获取Session值

使用Store.Get,Store.Set和Store.Del维护session

注意,正常情况下session值会在程序正常运行,返回至会话中间件时才进行更新和cookie变更。之间如果程序panic的话,之前的设置会失效

func(w http.ResponseWriter, r *http.Request) {
	err=store.Set(r,"sessionfieldname","new value")
	var v string
	//Get时需要传入指针
	err=store.Get(r,"sessionfieldname",&v)
	err=store.Del(r,"sessionfieldname")
}
Session对象

Session是一个存放了所有会话数据的可序列化的结构。

获取Session

获取和维护Session主要有两个方向

1.通过Session Store从http请求中获取

//获取session
s,err:=store.GetRequestSession(r)

//将请求中的Session进行保存
err=s.SaveRequestSession(r)

2.通过Session Store直接创建/维护Session

s:=session.NewSession(store,"token")
使用Session对象
err=s.Set("sessionfieldname","value)
var v string
err=s.Get("sessionfieldname",&v)
err=s.Del("sessionfieldname")
//获取session的token值

注意,session值的修改需要保存后才能存入store

维护Session对象
 //重置session除token外的所有数据
 s.Regenerate()
 //从Store中通过token加载Session
 err=s.Load()
 //保存Session
 err=s.Save()
 //删除SEssion
 err=s.DeleteAndSave()
Sesssion的token操作
//获取token
token,err:=s.Token()
token=s.MustToken()
//设置token
s.SetToken(token)
//重新生成token,需要设置Prefix,比如用户Id
err=s.RegenerateToken("prefix)
Field对象

Field对象是指指定字段名的session字段。

他的用途主要有两个,一个是为使用session的程序提供一个储存特定数据的接口,另一个是可以直接用来的进行用户的登录和登出

//创建field
field:=store.Field("fieldname)
//使用field数据
err=field.Set("value")
var v string
err=field.Get(&v)
//删除数据
err=field.Flush()

//实现用户接口
uid,err:=field.IdentifyRequest(r)
//实现用户登录接口
err=field.Login(w,r,"userid)
//实现用户登出接口
err=field.Logout(w,r)

Documentation

Overview

Package session is used to store user data in token based cache. It is normally used as user session or token. This package depands github.com/herb-go/herb/cache.

Index

Constants

View Source
const (
	//PrefixModeRaw prefix mode which dont convert prefix
	PrefixModeRaw = "raw"
	//PrefixModeMd5 prefix mode which  convert prefix to md5 sum
	PrefixModeMd5 = "md5"
	//PrefixModeEmpty prefix mode which  convert prefix to empty string
	PrefixModeEmpty = "empty"
)
View Source
const (
	//StoreModeCookie which store session token in cookie.
	StoreModeCookie = "cookie"
	//StoreModeHeader which store session token in header.
	StoreModeHeader = "header"
)
View Source
const DefaultTokenLength = 64

DefaultTokenLength default token length

View Source
const DriverNameCacheStore = "cache"

DriverNameCacheStore driver name for data store

View Source
const DriverNameClientStore = "cookie"

DriverNameClientStore driver name for client store

View Source
const FlagDefault = Flag(1)

FlagDefault default session flag

View Source
const FlagTemporay = Flag(3)

FlagTemporay Flag what stands for a Temporay sesson. For example,a login withour "remeber me".

View Source
const IVSize = 16

IVSize AES IV size

Variables

View Source
var (
	//ErrDataNotFound rasied when token data not found.
	ErrDataNotFound = errors.New("Data not found")
	//ErrDataTypeWrong rasied when the given model type is different form registered model type.
	ErrDataTypeWrong = errors.New("Data type wrong")
	//ErrNilPointer raised when data point to nil.
	ErrNilPointer = errors.New("Data point to nil")
)
View Source
var (
	//ErrTokenNotValidated raised when the given token is not validated(for example: token is empty string)
	ErrTokenNotValidated = errors.New("Token not validated")
	//ErrRequestTokenNotFound raised when token is not found in context.You should use cookiemiddle or headermiddle or your our function to install the token.
	ErrRequestTokenNotFound = errors.New("Request token not found.Did you forget use install middleware?")
	//ErrFeatureNotSupported raised when fearture is not supoprted.
	ErrFeatureNotSupported = errors.New("Feature is not supported")
)
View Source
var DefaultMarshaler = "msgpack"

DefaultMarshaler default session Marshaler

Functions

func AESDecrypt

func AESDecrypt(encrypted []byte, key []byte, iv []byte) (decrypted []byte, err error)

AESDecrypt decrypt data with given key and iv. Data will be unpadding with PKCS7Unpadding. Return decrypted data and any error if raised.

func AESDecryptBase64

func AESDecryptBase64(encrypted string, key []byte, iv []byte) (decrypted []byte, err error)

AESDecryptBase64 decrypt base64 encoded data with given key and iv. Data will be unpadding with PKCS7Unpadding. Return decrypted data and any error if raised.

func AESEncrypt

func AESEncrypt(unencrypted []byte, key []byte, iv []byte) (encrypted []byte, err error)

AESEncrypt aes encrypt with given data,key and iv. Data will be padding with PKCS7Padding Return encrytped data and any error if raised.

func AESEncryptBase64

func AESEncryptBase64(unencrypted []byte, key []byte, iv []byte) (encrypted string, err error)

AESEncryptBase64 aes encrypt with given data,key and iv. Data will be padding with PKCS7Padding Return base64 encoded encrytped data and any error if raised.

func AESNonceDecrypt

func AESNonceDecrypt(encrypted []byte, key []byte) (decrypted []byte, err error)

AESNonceDecrypt decrypt data with given key. IV will load form first bytes of data. Data will be unpadding with PKCS7Unpadding. Return decrypted data and any error if raised.

func AESNonceDecryptBase64

func AESNonceDecryptBase64(encrypted string, key []byte) (decrypted []byte, err error)

AESNonceDecryptBase64 decrypt base64 encoded data with given key. IV will load form first bytes of data. Data will be unpadding with PKCS7Unpadding. Return decrypted data and any error if raised.

func AESNonceEncrypt

func AESNonceEncrypt(unencrypted []byte, key []byte) (encrypted []byte, err error)

AESNonceEncrypt aes encrypt data with given key and random bytes as IV. Data will be padding with PKCS7Padding Random IV will prefix encryped data return encrypted data and any error if raisd.

func AESNonceEncryptBase64

func AESNonceEncryptBase64(unencrypted []byte, key []byte) (encrypted string, err error)

AESNonceEncryptBase64 aes encrypt data with given key and random bytes as IV. Data will be padding with PKCS7Padding Random IV will prefix encryped data return base64 encoded encrypted data and any error if raisd.

func AESTokenMarshaler

func AESTokenMarshaler(s *ClientDriver, ts *Session) (err error)

AESTokenMarshaler token marshaler which crypt data with AES Return error if raised

func AESTokenUnmarshaler

func AESTokenUnmarshaler(s *ClientDriver, v *Session) (err error)

AESTokenUnmarshaler token unmarshaler which crypt data with AES Return error if raised

func PKCS7Padding

func PKCS7Padding(data []byte, blockSize int) []byte

PKCS7Padding padding data as PKCS7 Reference http://blog.studygolang.com/167.html

func PKCS7Unpadding

func PKCS7Unpadding(data []byte) []byte

PKCS7Unpadding unpadding data as PKCS7 Reference http://blog.studygolang.com/167.html

Types

type CacheDriver

type CacheDriver struct {
	Cache          *cache.Cache //Cache which stores token data
	Length         int
	PrefixMode     string
	TokenGenerater func(s *CacheDriver, prefix string) (token string, err error) //Token name generate func
}

CacheDriver CacheDriver is the stuct store token data in cache.

func NewCacheDriver

func NewCacheDriver() *CacheDriver

NewCacheDriver create new cache driver

func (*CacheDriver) Close

func (s *CacheDriver) Close() error

Close Close cachestore and return any error if raised

func (*CacheDriver) ConvertPrefix

func (s *CacheDriver) ConvertPrefix(prefix string) (output string, err error)

ConvertPrefix convert prefix by driver prefix mode

func (*CacheDriver) Delete

func (s *CacheDriver) Delete(token string) error

Delete delete the token with given name. Return any error if raised.

func (*CacheDriver) GenerateToken

func (s *CacheDriver) GenerateToken(prefix string) (token string, err error)

GenerateToken generate new token name with given prefix. Return the new token name and error.

func (*CacheDriver) GetSessionToken

func (s *CacheDriver) GetSessionToken(ts *Session) (token string, err error)

GetSessionToken Get the token string from token data. Return token and any error raised.

func (*CacheDriver) Init

func (s *CacheDriver) Init(option CacheDriverOption) error

Init init cache driver with given option

func (*CacheDriver) Load

func (s *CacheDriver) Load(v *Session) (err error)

Load load a given session with token from store.

func (*CacheDriver) Save

func (s *CacheDriver) Save(ts *Session, ttl time.Duration) (err error)

Save save given session with given ttl to store. Return any error if raised.

type CacheDriverOption

type CacheDriverOption interface {
	ApplyTo(*CacheDriver) error
}

CacheDriverOption cache driver init option interface.

type CacheDriverOptionConfig

type CacheDriverOptionConfig struct {
	Cache      *cache.Cache
	Length     int
	PrefixMode string
}

CacheDriverOptionConfig cache driver init option

func NewCacheDriverOptionConfig

func NewCacheDriverOptionConfig() *CacheDriverOptionConfig

NewCacheDriverOptionConfig create new cache driver init option

func (*CacheDriverOptionConfig) ApplyTo

func (o *CacheDriverOptionConfig) ApplyTo(d *CacheDriver) error

ApplyTo apply cache driver option config to cache driver. return any error if raised.

type ClientDriver

type ClientDriver struct {
	Key              []byte                              //Crypt key
	TokenMarshaler   func(*ClientDriver, *Session) error //Marshler data to Session.token
	TokenUnmarshaler func(*ClientDriver, *Session) error //Unmarshler data from Session.token
}

ClientDriver ClientDriver is the stuct store token data in Client side.

func NewClientDriver

func NewClientDriver() *ClientDriver

NewClientDriver New create a new client side token store with given key and token lifetime. Key the key used to encrpty data TokenLifeTime is the token initial expired tome. Return a new token store. All other property of the store can be set after creation.

func (*ClientDriver) Close

func (s *ClientDriver) Close() error

Close Close cachestore and return any error if raised

func (*ClientDriver) Delete

func (s *ClientDriver) Delete(token string) error

Delete delete the token with given name. Return any error if raised.

func (*ClientDriver) GenerateToken

func (s *ClientDriver) GenerateToken(prefix string) (token string, err error)

GenerateToken generate new token name with given prefix. Return the new token name and error.

func (*ClientDriver) GetSessionToken

func (s *ClientDriver) GetSessionToken(ts *Session) (token string, err error)

GetSessionToken Get the token string from token data. Return token and any error raised.

func (*ClientDriver) Init

func (s *ClientDriver) Init(option ClientDriverOption) error

Init init client driver with given option. Return any error if raised.

func (*ClientDriver) Load

func (s *ClientDriver) Load(v *Session) (err error)

Load Load Session form the Session.token. Return any error if raised

func (*ClientDriver) Save

func (s *ClientDriver) Save(ts *Session, ttl time.Duration) (err error)

Save Save Session if necessary. Return any error raised.

type ClientDriverOption

type ClientDriverOption interface {
	ApplyTo(*ClientDriver) error
}

ClientDriverOption client driver init option interface.

type ClientDriverOptionConfig

type ClientDriverOptionConfig struct {
	Key []byte
}

ClientDriverOptionConfig client driver init option.

func NewClientDriverOptionConfig

func NewClientDriverOptionConfig() *ClientDriverOptionConfig

NewClientDriverOptionConfig create new client driver init option.

func (*ClientDriverOptionConfig) ApplyTo

ApplyTo apply client driver option config to cache driver. return any error if raised.

type ContextKey

type ContextKey string

ContextKey string type used in Context key

type Driver

type Driver interface {
	GetSessionToken(ts *Session) (token string, err error)
	GenerateToken(owner string) (token string, err error)
	Load(v *Session) error
	Save(t *Session, ttl time.Duration) error
	Delete(token string) error
	Close() error
}

Driver store driver.

type Field

type Field struct {
	Store *Store
	Name  string
}

Field session field struct

func (*Field) Flush

func (f *Field) Flush(r *http.Request) (err error)

Flush flush session store in given http request. Return any error if raised.

func (*Field) Get

func (f *Field) Get(r *http.Request, v interface{}) (err error)

Get get value from session store in given http request and save to v. Return any error if raised.

func (*Field) GetSession

func (f *Field) GetSession(r *http.Request) (ts *Session, err error)

GetSession get Session from http request. Return session and any error if raised.

func (*Field) IdentifyRequest

func (f *Field) IdentifyRequest(r *http.Request) (string, error)

IdentifyRequest indentify request with field. Return id and any error if raised.

func (*Field) LoadFrom

func (f *Field) LoadFrom(ts *Session, v interface{}) (err error)

LoadFrom load value form given session. Return any error if raised.

func (*Field) Login

func (f *Field) Login(w http.ResponseWriter, r *http.Request, id string) error

Login login to request with given id. Return any error if raised.

func (*Field) Logout

func (f *Field) Logout(w http.ResponseWriter, r *http.Request) error

Logout logout form request.

func (*Field) SaveTo

func (f *Field) SaveTo(ts *Session, v interface{}) (err error)

SaveTo save value to given session. Return any error if raised.

func (*Field) Set

func (f *Field) Set(r *http.Request, v interface{}) (err error)

Set set value to session store in given http request. Return any error if raised.

type Flag

type Flag uint64

Flag Flag used when saving session

type Option

type Option interface {
	ApplyTo(*Store) error
}

Option store init option interface.

type OptionConfig

type OptionConfig struct {
	Driver        Driver
	TokenLifetime time.Duration
}

OptionConfig store init config

func NewOptionConfig

func NewOptionConfig() *OptionConfig

NewOptionConfig create new store init config

func (*OptionConfig) ApplyTo

func (o *OptionConfig) ApplyTo(s *Store) error

ApplyTo apply config to sessoion store

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
}

ResponseWriter http response writer

type Session

type Session struct {
	ExpiredAt      int64 //Timestamp when the token expired.
	CreatedTime    int64 //Timestamp when the token created.
	LastActiveTime int64 //Timestamp when the token Last Active.

	Store *Store
	Nonce []byte
	Flag  Flag
	Mutex *sync.RWMutex //Read write mutex.
	// contains filtered or unexported fields
}

Session Token data in every request.

func NewSession

func NewSession(token string, s *Store) *Session

NewSession create new token data in store with given name. token the token name. s the store which token data belongs to. return new Session.

func (*Session) Del

func (s *Session) Del(name string) (err error)

Del delete value form session with given name.

func (*Session) DeleteAndSave

func (s *Session) DeleteAndSave() error

DeleteAndSave Delete token.

func (*Session) Get

func (s *Session) Get(name string, v interface{}) (err error)

Get load data model from given token data. Parameter v should be pointer to empty data model which data filled in. Return any error raised.

func (*Session) HasFlag

func (s *Session) HasFlag(flag Flag) bool

HasFlag verify if session has given flag.

func (*Session) Load

func (s *Session) Load() error

Load the token data from cache. Repeat call Load will only load data once. Return any error raised.

func (*Session) Marshal

func (s *Session) Marshal() ([]byte, error)

Marshal convert Session to bytes. Return Converted bytes and any error raised.

func (*Session) MustToken

func (s *Session) MustToken() string

MustToken return the toke name.

func (*Session) Regenerate

func (s *Session) Regenerate()

Regenerate reset all session values except token

func (*Session) RegenerateToken

func (s *Session) RegenerateToken(owner string) error

RegenerateToken create new token and token data with given owner. Return any error raised.

func (*Session) Save

func (s *Session) Save() error

Save Save token data to cache. Won't do anything if token data not changed. You should call Save manually in your token binding func or non http request usage.

func (*Session) Set

func (s *Session) Set(name string, v interface{}) (err error)

Set set value to session with given name. Return any error if rasied.

func (*Session) SetCache

func (s *Session) SetCache(name string, v interface{})

SetCache set cached value to session with given name and value.

func (*Session) SetFlag

func (s *Session) SetFlag(flag Flag, value bool)

SetFlag Set a flag to session.

func (*Session) SetToken

func (s *Session) SetToken(newToken string)

SetToken update token name

func (*Session) Token

func (s *Session) Token() (string, error)

Token return the toke name. Return any error raised.

func (*Session) Unmarshal

func (s *Session) Unmarshal(token string, bytes []byte) error

Unmarshal Unmarshal bytes to Session. All data in session will be overwrited. Return any error raised.

type Store

type Store struct {
	Driver               Driver
	Marshaler            cache.Marshaler
	TokenLifetime        time.Duration //Token initial expired time.Token life time can be refreshed when accessed if UpdateActiveInterval is greater than 0.
	TokenMaxLifetime     time.Duration //Token max life time.Token can't live more than TokenMaxLifetime if TokenMaxLifetime if greater than 0.
	TokenContextName     ContextKey    //Name in request context store the token  data.Default Session is "token".
	CookieName           string        //Cookie name used in CookieMiddleware.Default Session is "herb-session".
	CookiePath           string        //Cookie path used in cookieMiddleware.Default Session is "/".
	CookieSecure         bool          //Cookie secure value used in cookie middleware.
	AutoGenerate         bool          //Whether auto generate token when guset visit.Default Session is false.
	Mode                 string        //Mode used in auto install middleware.
	UpdateActiveInterval time.Duration //The interval between what token active time refreshed.If less than or equal to 0,the token life time will not be refreshed.
	DefaultSessionFlag   Flag          //Default flag when creating session.
}

Store Basic token store interface

func MustCacheStore

func MustCacheStore(Cache *cache.Cache, TokenLifetime time.Duration) *Store

MustCacheStore create new data store with given token lifetime. Return store created. Panic if any error raised.

func MustClientStore

func MustClientStore(key []byte, TokenLifetime time.Duration) *Store

MustClientStore create new client store with given key and ttl. Return store created. Panic if any error raised.

func New

func New() *Store

New create empty session store.

func (*Store) AutoGenerateMiddleware

func (s *Store) AutoGenerateMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

AutoGenerateMiddleware middleware that auto generate session.

func (*Store) Close

func (s *Store) Close() error

Close Close cachestore and return any error if raised

func (*Store) CookieMiddleware

func (s *Store) CookieMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

CookieMiddleware return a Middleware which install the token which special by cookie. This middleware will save token after request finished if the token changed,and update cookie if necessary.

func (*Store) Del

func (s *Store) Del(r *http.Request, fieldName string) (err error)

Del delete value from request with given field name. Return any error if raised.

func (*Store) DeleteToken

func (s *Store) DeleteToken(token string) error

DeleteToken delete the token with given name. Return any error if raised.

func (*Store) DestoryMiddleware

func (s *Store) DestoryMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

DestoryMiddleware return a middleware clear the token in request.

func (*Store) ExpiredAt

func (s *Store) ExpiredAt(r *http.Request) (ExpiredAt int64, err error)

ExpiredAt get session expired timestamp from rerquest. Return expired timestamp and any error if raised.

func (*Store) Field

func (s *Store) Field(name string) *Field

Field create store field with given name. Return field created.

func (*Store) GenerateSession

func (s *Store) GenerateSession(token string) (ts *Session, err error)

GenerateSession generate new token data with given token. Return a new Session and error.

func (*Store) GenerateToken

func (s *Store) GenerateToken(prefix string) (token string, err error)

GenerateToken generate new token name with given prefix. Return the new token name and error.

func (*Store) Get

func (s *Store) Get(r *http.Request, fieldName string, v interface{}) (err error)

Get get value form request with given field name. Return any error if raised.

func (*Store) GetRequestSession

func (s *Store) GetRequestSession(r *http.Request) (ts *Session, err error)

GetRequestSession get stored token data from request. Return the stored token data and any error raised.

func (*Store) GetSession

func (s *Store) GetSession(token string) (ts *Session)

GetSession get the token data with give token . Return the Session

func (*Store) GetSessionToken

func (s *Store) GetSessionToken(ts *Session) (token string, err error)

GetSessionToken Get the token string from token data. Return token and any error raised.

func (*Store) HeaderMiddleware

func (s *Store) HeaderMiddleware(Name string) func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

HeaderMiddleware return a Middleware which install the token which special by Header with given name. This middleware will save token after request finished if the token changed.

func (*Store) Init

func (s *Store) Init(option Option) error

Init init store with given option.

func (*Store) Install

func (s *Store) Install(r *http.Request, token string) (ts *Session, err error)

Install install the give token to request. Session will be stored in request context which named by TokenContextName of store. You should use this func when use your own token binding func instead of CookieMiddleware or HeaderMiddleware Return the loaded Session and any error raised.

func (*Store) InstallMiddleware

func (s *Store) InstallMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

InstallMiddleware middleware which auto install session depand on store mode. Cookie middleware will be installed if no valid store mode given.

func (Store) IsNotFoundError

func (s Store) IsNotFoundError(err error) bool

IsNotFoundError return if given error if a not found error.

func (*Store) LoadSession

func (s *Store) LoadSession(v *Session) error

LoadSession Load Session form the Session.token. Return any error if raised

func (*Store) RegenerateToken

func (s *Store) RegenerateToken(prefix string) (ts *Session, err error)

RegenerateToken regenerate session token with given prefix. Return session and any error if raised.

func (*Store) SaveRequestSession

func (s *Store) SaveRequestSession(r *http.Request) error

SaveRequestSession save the request token data.

func (*Store) SaveSession

func (s *Store) SaveSession(t *Session) error

SaveSession Save Session if necessary. Return any error raised.

func (*Store) Set

func (s *Store) Set(r *http.Request, fieldName string, v interface{}) (err error)

Set set value to request with given field name. Return any error if raised.

type StoreConfig

type StoreConfig struct {
	DriverName                   string
	Marshaler                    string
	Mode                         string
	TokenLifetimeInHour          int64  //Token initial expired time in second.Token life time can be update when accessed if UpdateActiveInterval is greater than 0.
	TokenLifetimeInDay           int64  //Token initial expired time in day.Token life time can be update when accessed if UpdateActiveInterval is greater than 0.Skipped if  TokenLifetimeInHour is set.
	TokenMaxLifetimeInDay        int64  //Token max life time.Token can't live more than TokenMaxLifetime if TokenMaxLifetime if greater than 0.
	TokenContextName             string //Name in request context store the token  data.Default Session is "token".
	CookieName                   string //Cookie name used in CookieMiddleware.Default Session is "herb-session".
	CookiePath                   string //Cookie path used in cookieMiddleware.Default Session is "/".
	CookieSecure                 bool   //Cookie secure value used in cookie middleware.
	AutoGenerate                 bool   //Whether auto generate token when guset visit.Default Session is false.
	UpdateActiveIntervalInSecond int64  //The interval between who token active time update.If less than or equal to 0,the token life time will not be refreshed.
	DefaultSessionFlag           Flag   //Default flag when creating session.
	ClientStoreKey               string
	TokenPrefixMode              string
	TokenLength                  int
	Cache                        cache.OptionConfigMap
}

StoreConfig store config struct.

func (*StoreConfig) ApplyTo

func (s *StoreConfig) ApplyTo(store *Store) error

ApplyTo apply config to store. Return any error if raised.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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