session

package module
v0.0.0-...-63d36b1 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2019 License: MIT Imports: 8 Imported by: 0

README

session

Build Status

session for golang, it can use signed cookie by keygrip.

API

New(req *http.Request, res http.ResponseWriter, opts *Options)

Create a cookie instance

  • req http request
  • res http response writer
  • opts.Key cookie key, default is sess
  • opts.MaxAge the max age for session data(seconds)
  • opts.Store the session store
  • opts.GenID function to generate session id(cookie's value), if not set, it will use ulid.
  • opts.CookieOptions cookies.Options
store := session.NewRedisStore(nil, &redis.Options{
  Addr: "localhost:6379",
})
r := httptest.NewRequest(http.MethodGet, "http://aslant.site/api/users/me", nil)
w := httptest.NewRecorder()
rw := cookies.NewHTTPReadWriter(r, w)
sess := session.New(rw, &Options{
  Store: store,
  CookieOptions: &cookies.Options{
    Keys: []string{
      "tree.xie",
    },
  },
})
store, _ := session.NewMemoryStore(10240)
r := httptest.NewRequest(http.MethodGet, "http://aslant.site/api/users/me", nil)
w := httptest.NewRecorder()
rw := cookies.NewHTTPReadWriter(r, w)
sess := session.New(rw, &Options{
  Store: store,
  CookieOptions: &cookies.Options{
    Keys: []string{
      "tree.xie",
    },
  },
})
Fetch()

Fetch the session data from redis

data, err := sess.Fetch()
Refresh()

Refresh the session, it just change the updatedAt of session. The function should be called after Fetch.

err := sess.Refresh()
Set(key string, value interface{})

Set the data to session, if Fetch isn't called, ErrNotFetched will return.

The key UpdatedAt will be set to date string of now when Set call succeed.

err := sess.Set("name", "tree.xie")
SetMap(value map[string]interface{})
err := sess.Set(map[string]interface{}{
  "a": 1,
  "b": "2",
  "c": true,
})
Get(key string)

Get the data from session, if Fetch isn't called, it will return nil.

i := sess.Get("name")
GetBool(key string)

Get the bool data from session.

exitst := sess.GetBool("exists")
GetString(key string)

Get the string data from session.

name := sess.GetBool("name")
GetInt(key string)

Get the int data from session.

age := sess.GetInt("age")
GetFloat64(key string)

Get the float64 data from session.

count := sess.GetFloat64("count")
GetStringSlice(key string)

Get the string slice from session.

category := sess.GetStringSlice("category")
GetCreatedAt

Get the created at field from session, if Fetch isn't called, it will be "".

createdAt := sess.GetCreatedAt()
GetUpdatedAt

Get the updated at field from session, if Fetch isn't called, it will be "".

updatedAt := sess.GetUpdatedAt()
Commit

Commit the data to store when it's be modified.

If the first time create session, it will set the cookie for session.

store := session.NewRedisStore(nil, &redis.Options{
  Addr: "localhost:6379",
})
r := httptest.NewRequest(http.MethodGet, "http://aslant.site/api/users/me", nil)
w := httptest.NewRecorder()
rw := cookies.NewHTTPReadWriter(r, w)
sess := session.New(rw, &Options{
  Store: store,
  CookieOptions: &cookies.Options{
    Keys: []string{
      "tree.xie",
    },
  },
})
_, err := sess.Fetch()
if err != nil {
  fmt.Printf("fetch sesion fail, %v", err)
}
sess.Set("name", "tree.xie")
err = sess.Commit()
if err != nil {
  fmt.Printf("commit sesion fail, %v", err)
}
Destroy

Remove the data from store and reset session data

err := sess.Destroy()

test

go test -race -coverprofile=test.out ./... && go tool cover --html=test.out

Documentation

Index

Constants

View Source
const (

	// CreatedAt the created time for session
	CreatedAt = "_createdAt"
	// UpdatedAt the updated time for session
	UpdatedAt = "_updatedAt"
)

Variables

View Source
var (
	// ErrNotFetched not fetch error
	ErrNotFetched = errors.New("Not fetch session")
)
View Source
var (
	// ErrNotInit error not init
	ErrNotInit = errors.New("client not init")
)

Functions

This section is empty.

Types

type JSON

type JSON interface {
	Unmarshal([]byte, interface{}) error
	Marshal(interface{}) ([]byte, error)
}

JSON json Unmarshal/Marshal

type M

type M map[string]interface{}

M alias

type MemoryStore

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

MemoryStore memory store for session

func NewMemoryStore

func NewMemoryStore(size int) (store *MemoryStore, err error)

NewMemoryStore create new memory store instance

func (*MemoryStore) Destroy

func (ms *MemoryStore) Destroy(key string) (err error)

Destroy remove the session from memory

func (*MemoryStore) Get

func (ms *MemoryStore) Get(key string) (data []byte, err error)

Get get the seesion from memory

func (*MemoryStore) Set

func (ms *MemoryStore) Set(key string, data []byte, ttl int) (err error)

Set set the sesion to memory

type MemoryStoreInfo

type MemoryStoreInfo struct {
	ExpiredAt int64
	Data      []byte
}

MemoryStoreInfo memory store info

type Options

type Options struct {
	// cookie key, default is sess
	Key string
	// the max age for session data
	MaxAge int
	// the session store
	Store Store
	// function to generate session id
	GenID         func() string
	CookieOptions *cookies.Options
	// JSON json Unmarshal/Marshal interface
	JSON JSON
}

Options new session options

type RedisStore

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

RedisStore redis store for session

func NewRedisStore

func NewRedisStore(client *redis.Client, opts *redis.Options) *RedisStore

NewRedisStore create new redis store instance

func (*RedisStore) Destroy

func (rs *RedisStore) Destroy(key string) error

Destroy remove the session from redis

func (*RedisStore) Get

func (rs *RedisStore) Get(key string) ([]byte, error)

Get get the session from redis

func (*RedisStore) Set

func (rs *RedisStore) Set(key string, data []byte, ttl int) error

Set set the session to redis

type Session

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

Session session struct

func Mock

func Mock(data M) *Session

Mock mock a session

func New

func New(rw cookies.ReadWriter, opts *Options) *Session

New create a session instance

func (*Session) Commit

func (sess *Session) Commit() (err error)

Commit sync the session to store

func (*Session) Destroy

func (sess *Session) Destroy() (err error)

Destroy remove the data from store and reset session data

func (*Session) Fetch

func (sess *Session) Fetch() (m M, err error)

Fetch fetch the session data from store

func (*Session) Get

func (sess *Session) Get(key string) interface{}

Get get data from session's data

func (*Session) GetBool

func (sess *Session) GetBool(key string) bool

GetBool get bool data from session's data

func (*Session) GetCreatedAt

func (sess *Session) GetCreatedAt() string

GetCreatedAt get the created at of session

func (*Session) GetData

func (sess *Session) GetData() M

GetData get the session's data

func (*Session) GetFloat64

func (sess *Session) GetFloat64(key string) float64

GetFloat64 get float64 data from session's data

func (*Session) GetInt

func (sess *Session) GetInt(key string) int

GetInt get int data from session's data

func (*Session) GetString

func (sess *Session) GetString(key string) string

GetString get string data from session's data

func (*Session) GetStringSlice

func (sess *Session) GetStringSlice(key string) []string

GetStringSlice get string slice data from session's data

func (*Session) GetUpdatedAt

func (sess *Session) GetUpdatedAt() string

GetUpdatedAt get the updated at of session

func (*Session) Refresh

func (sess *Session) Refresh() (err error)

Refresh refresh session (update updatedAt)

func (*Session) RegenerateCookie

func (sess *Session) RegenerateCookie()

RegenerateCookie regenerate the session's cookie

func (*Session) Set

func (sess *Session) Set(key string, value interface{}) (err error)

Set set data to session

func (*Session) SetMap

func (sess *Session) SetMap(value map[string]interface{}) (err error)

SetMap set map data to session

type Store

type Store interface {
	// Get get the session data
	Get(string) ([]byte, error)
	// Set set the session data
	Set(string, []byte, int) error
	// Destroy remove the session data
	Destroy(string) error
}

Store session store interface

Jump to

Keyboard shortcuts

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