sessions

package module
v0.0.0-...-1c51e5f Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2019 License: MIT Imports: 15 Imported by: 3

README

sessions

Build Status codecov Go Report Card GoDoc

Gin middleware for session management with multi-backend support (currently cookie, Redis, Memcached, MongoDB, memstore).

Usage

Start using it

Download and install it:

$ go get github.com/penggy/sessions

Import it in your code:

import "github.com/penggy/sessions"

Examples

package main

import (
	"github.com/penggy/sessions"
	"github.com/penggy/sessions/cookie"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	store := cookie.NewStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/incr", func(c *gin.Context) {
		session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})
	r.Run(":8000")
}
Redis
package main

import (
	"github.com/penggy/sessions"
	"github.com/penggy/sessions/redis"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/incr", func(c *gin.Context) {
		session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})
	r.Run(":8000")
}
Memcached
package main

import (
	"github.com/bradfitz/gomemcache/memcache"
	"github.com/penggy/sessions"
	"github.com/penggy/sessions/memcached"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	store := memcached.NewStore(memcache.New("localhost:11211"), "", []byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/incr", func(c *gin.Context) {
		session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})
	r.Run(":8000")
}
MongoDB
package main

import (
	"github.com/penggy/sessions"
	"github.com/penggy/sessions/mongo"
	"github.com/gin-gonic/gin"
	"gopkg.in/mgo.v2"
)

func main() {
	r := gin.Default()
	session, err := mgo.Dial("localhost:27017/test")
	if err != nil {
		// handle err
	}

	c := session.DB("").C("sessions")
	store := mongo.NewStore(c, 3600, true, []byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/incr", func(c *gin.Context) {
		session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})
	r.Run(":8000")
}
memstore
package main

import (
	"github.com/penggy/sessions"
	"github.com/penggy/sessions/memstore"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	store := memstore.NewStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/incr", func(c *gin.Context) {
		session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})
	r.Run(":8000")
}

Documentation

Index

Constants

View Source
const (
	DefaultKey = "github.com/MeloQi/sessions"
)

Variables

This section is empty.

Functions

func GorillaSessions

func GorillaSessions(name string, store Store) gin.HandlerFunc

func Sessions

func Sessions(name string, store Store) gin.HandlerFunc

Types

type GormStore

type GormStore struct {
	Codecs      []securecookie.Codec
	SessionOpts *gsessions.Options
	// contains filtered or unexported fields
}

Store represent a gormstore

func NewGormStore

func NewGormStore(db *gorm.DB, keyPairs ...[]byte) *GormStore

New creates a new gormstore session

func NewGormStoreWithOptions

func NewGormStoreWithOptions(db *gorm.DB, opts GormStoreOptions, keyPairs ...[]byte) *GormStore

NewOptions creates a new gormstore session with options

func (*GormStore) Cleanup

func (st *GormStore) Cleanup()

Cleanup deletes expired sessions

func (*GormStore) Get

func (st *GormStore) Get(r *http.Request, name string) (*gsessions.Session, error)

Get returns a session for the given name after adding it to the registry.

func (*GormStore) MaxAge

func (st *GormStore) MaxAge(age int)

MaxAge sets the maximum age for the store and the underlying cookie implementation. Individual sessions can be deleted by setting Options.MaxAge = -1 for that session.

func (*GormStore) MaxLength

func (st *GormStore) MaxLength(l int)

MaxLength restricts the maximum length of new sessions to l. If l is 0 there is no limit to the size of a session, use with caution. The default is 4096 (default for securecookie)

func (*GormStore) New

func (st *GormStore) New(r *http.Request, name string) (*gsessions.Session, error)

New creates a session with name without adding it to the registry.

func (*GormStore) Options

func (st *GormStore) Options(options Options)

func (*GormStore) RenewID

func (st *GormStore) RenewID(r *http.Request, w http.ResponseWriter, session *gsessions.Session) error

func (*GormStore) Save

func (st *GormStore) Save(r *http.Request, w http.ResponseWriter, session *gsessions.Session) error

Save session and set cookie header

type GormStoreOptions

type GormStoreOptions struct {
	TableName       string
	SkipCreateTable bool
}

Options for gormstore

type JSONSerializer

type JSONSerializer struct{}

JSONSerializer encode the session map to JSON.

func (JSONSerializer) Deserialize

func (s JSONSerializer) Deserialize(d []byte, ss *gsessions.Session) error

Deserialize back to map[string]interface{}

func (JSONSerializer) Serialize

func (s JSONSerializer) Serialize(ss *gsessions.Session) ([]byte, error)

Serialize to JSON. Will err if there are unmarshalable key values

type Options

type Options struct {
	Path   string
	Domain string
	// MaxAge=0 means no 'Max-Age' attribute specified.
	// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'.
	// MaxAge>0 means Max-Age attribute present and given in seconds.
	MaxAge   int
	Secure   bool
	HttpOnly bool
}

Options stores configuration for a session or session store. Fields are a subset of http.Cookie fields.

type RediStore

type RediStore struct {
	RedisClient    *redis.Client
	Codecs         []securecookie.Codec
	SessionOptions *gsessions.Options // default configuration
	DefaultMaxAge  int                // default Redis TTL for a MaxAge == 0 session
	// contains filtered or unexported fields
}

RediStore stores sessions in a redis backend.

func NewRediStore

func NewRediStore(client *redis.Client, keyPrefix string, keyPairs ...[]byte) *RediStore

func (*RediStore) Get

func (s *RediStore) Get(r *http.Request, name string) (*gsessions.Session, error)

Get returns a session for the given name after adding it to the registry.

See gorilla/sessions FilesystemStore.Get().

func (*RediStore) New

func (s *RediStore) New(r *http.Request, name string) (*gsessions.Session, error)

New returns a session for the given name without adding it to the registry.

See gorilla/sessions FilesystemStore.New().

func (*RediStore) Options

func (s *RediStore) Options(options Options)

func (*RediStore) RenewID

func (s *RediStore) RenewID(r *http.Request, w http.ResponseWriter, session *gsessions.Session) error

func (*RediStore) Save

func (s *RediStore) Save(r *http.Request, w http.ResponseWriter, session *gsessions.Session) error

Save adds a single session to the response.

func (*RediStore) SetMaxAge

func (s *RediStore) SetMaxAge(v int)

SetMaxAge restricts the maximum age, in seconds, of the session record both in database and a browser. This is to change session storage configuration. If you want just to remove session use your session `s` object and change it's `Options.MaxAge` to -1, as specified in

http://godoc.org/github.com/gorilla/sessions#Options

Default is the one provided by this package value - `sessionExpire`. Set it to 0 for no restriction. Because we use `MaxAge` also in SecureCookie crypting algorithm you should use this function to change `MaxAge` value.

func (*RediStore) SetMaxLength

func (s *RediStore) SetMaxLength(l int)

SetMaxLength sets RediStore.maxLength if the `l` argument is greater or equal 0 maxLength restricts the maximum length of new sessions to l. If l is 0 there is no limit to the size of a session, use with caution. The default for a new RediStore is 4096. Redis allows for max. value sizes of up to 512MB (http://redis.io/topics/data-types) Default: 4096,

func (*RediStore) SetSerializer

func (s *RediStore) SetSerializer(ss SessionSerializer)

SetSerializer sets the serializer

type Session

type Session interface {
	// Get returns the session value associated to the given key.
	Get(key interface{}) interface{}
	// Set sets the session value associated to the given key.
	Set(key interface{}, val interface{})
	// Delete removes the session value associated to the given key.
	Delete(key interface{})
	// Clear deletes all values in the session.
	Clear()
	// AddFlash adds a flash message to the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	AddFlash(value interface{}, vars ...string)
	// Flashes returns a slice of flash messages from the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	Flashes(vars ...string) []interface{}
	// Options sets confuguration for a session.
	Options(Options)
	// Save saves all sessions used during the current request.
	Save() error

	RenewID() (string, error)

	ID() string

	SetMaxAge(maxAge int)

	Destroy()
}

Wraps thinly gorilla-session methods. Session stores the values and optional configuration for a session.

func Default

func Default(c *gin.Context) Session

shortcut to get session

type SessionSerializer

type SessionSerializer interface {
	Deserialize(d []byte, ss *gsessions.Session) error
	Serialize(ss *gsessions.Session) ([]byte, error)
}

SessionSerializer provides an interface hook for alternative serializers

type Store

type Store interface {
	sessions.Store
	RenewID(r *http.Request, w http.ResponseWriter, gsession *sessions.Session) error
	Options(Options)
}

Jump to

Keyboard shortcuts

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