session

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2018 License: MIT Imports: 14 Imported by: 0

README

session

Build Status Coverage Status Go Report Card GoDoc

Session Middleware for Golang

For Go1.10 below please use version 0.11, 0.12 will support only Go1.11 onward.

Example with Middleware

package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/acoshift/session"
	store "github.com/acoshift/session/store/memory"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/" {
			http.NotFound(w, r)
			return
		}

		s, _ := session.Get(r.Context(), "sess")
		cnt := s.GetInt("counter")
		cnt++
		s.Set("counter", cnt)
		w.Header().Set("Content-Type", "text/html")
		fmt.Fprintf(w, "Couter: %d<br><a href=\"/reset\">Reset</a>", cnt)
	})
	mux.HandleFunc("/reset", func(w http.ResponseWriter, r *http.Request) {
		s, _ := session.Get(r.Context(), "sess")
		s.Del("counter")
		http.Redirect(w, r, "/", http.StatusFound)
	})

	h := session.Middleware(session.Config{
		Domain:   "localhost",
		HTTPOnly: true,
		Secret:   []byte("testsecret1234"),
		MaxAge:   time.Minute,
		Path:     "/",
		Secure:   session.PreferSecure,
		Store:    store.New(store.Config{}),
	})(mux)
	// equals to
	// h := session.New(session.Config{...}).Middleware()(mux)

	log.Fatal(http.ListenAndServe(":8080", h))
}

Example with Manager

package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/acoshift/session"
	store "github.com/acoshift/session/store/memory"
)

func main() {
	mux := http.NewServeMux()

	m := session.New(session.Config{
		Domain:   "localhost",
		HTTPOnly: true,
		Secret:   []byte("testsecret1234"),
		MaxAge:   time.Minute,
		Path:     "/",
		Secure:   session.PreferSecure,
		Store:    store.New(store.Config{}),
	})

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/" {
			http.NotFound(w, r)
			return
		}

		s, _ := m.Get(r, "sess")
		cnt := s.GetInt("counter")
		cnt++
		s.Set("counter", cnt)
		m.Save(w, s)
		w.Header().Set("Content-Type", "text/html")
		fmt.Fprintf(w, "Couter: %d<br><a href=\"/reset\">Reset</a>", cnt)
	})
	mux.HandleFunc("/reset", func(w http.ResponseWriter, r *http.Request) {
		s, _ := m.Get(r, "sess")
		s.Del("counter")
		m.Save(w, s)
		http.Redirect(w, r, "/", http.StatusFound)
	})

	log.Fatal(http.ListenAndServe(":8080", mux))
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is the error when session not found
	// store must return ErrNotFound if session data not exists
	ErrNotFound = errors.New("session: not found")
)

Errors

View Source
var (
	ErrNotPassMiddleware = errors.New("session: request not pass middleware")
)

Errors

View Source
var (
	HijackedTime = 5 * time.Minute
)

Global Session Config

Functions

func Middleware

func Middleware(config Config) func(http.Handler) http.Handler

Middleware is the Manager middleware wrapper

New(config).Middleware()

Types

type Config

type Config struct {
	Store Store

	// Secret is the salt for hash session id before put to store
	Secret []byte

	// Keys is the keys to sign session id
	Keys [][]byte

	// Cookie config
	Domain   string
	HTTPOnly bool
	Path     string
	MaxAge   time.Duration
	Secure   Secure
	SameSite http.SameSite

	// IdleTimeout is the ttl for storage
	// if IdleTimeout is zero, it will use MaxAge
	IdleTimeout time.Duration

	// DeleteOldSession deletes the old session from store when regenerate,
	// better not to delete old session to avoid user loss session when unstable network
	DeleteOldSession bool

	// Resave forces session to save to store even if session was not modified
	Resave bool

	// Rolling, set cookie every responses
	Rolling bool

	// Proxy, also checks X-Forwarded-Proto when use prefer secure
	Proxy bool

	// DisablaHashID disables hash session id when save to store
	DisableHashID bool

	// GenerateID is the generate id function
	GenerateID func() string
}

Config is the session manager config

type Data added in v0.5.0

type Data map[string]interface{}

Data stores session data

func (Data) Clone added in v0.5.0

func (data Data) Clone() Data

Clone clones session data

type Manager added in v0.2.0

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

Manager is the session manager

func New added in v0.2.0

func New(config Config) *Manager

New creates new session manager

func (*Manager) Get added in v0.2.0

func (m *Manager) Get(r *http.Request, name string) (*Session, error)

Get retrieves session from request

func (*Manager) Middleware added in v0.4.0

func (m *Manager) Middleware() func(http.Handler) http.Handler

Middleware injects session manager into request's context.

All data changed before write response writer's header will be save.

func (*Manager) Save added in v0.2.0

func (m *Manager) Save(w http.ResponseWriter, s *Session) error

Save saves session to store and set cookie to response

Save must be called before response header was written

type Secure

type Secure int

Secure config

const (
	NoSecure     Secure = iota
	PreferSecure        // if request is https will set secure cookie
	ForceSecure         // always set secure cookie
)

Secure values

type Session

type Session struct {

	// cookie config
	Name     string
	Domain   string
	Path     string
	HTTPOnly bool
	MaxAge   time.Duration
	Secure   bool
	SameSite http.SameSite
	Rolling  bool
	// contains filtered or unexported fields
}

Session type

func Get

func Get(ctx context.Context, name string) (*Session, error)

Get gets session from context

func (*Session) Changed added in v0.4.0

func (s *Session) Changed() bool

Changed returns is session data changed

func (*Session) Del

func (s *Session) Del(key string)

Del deletes data from session

func (*Session) Destroy added in v0.0.4

func (s *Session) Destroy()

Destroy destroys session from store

func (*Session) Flash added in v0.3.0

func (s *Session) Flash() *flash.Flash

Flash returns flash from session

func (*Session) Get

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

Get gets data from session

func (*Session) GetBool added in v0.5.0

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

GetBool gets bool from session

func (*Session) GetFloat32 added in v0.5.0

func (s *Session) GetFloat32(key string) float32

GetFloat32 gets float32 from session

func (*Session) GetFloat64 added in v0.5.0

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

GetFloat64 gets float64 from session

func (*Session) GetInt added in v0.5.0

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

GetInt gets int from session

func (*Session) GetInt64 added in v0.5.0

func (s *Session) GetInt64(key string) int64

GetInt64 gets int64 from session

func (*Session) GetString added in v0.5.0

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

GetString gets string from session

func (*Session) Hijacked added in v0.4.0

func (s *Session) Hijacked() bool

Hijacked checks is session was hijacked, can use only with Manager

func (*Session) ID added in v0.4.0

func (s *Session) ID() string

ID returns session id or hashed session id if enable hash id

func (*Session) IsNew added in v0.5.0

func (s *Session) IsNew() bool

IsNew checks is new session

func (*Session) Pop added in v0.4.0

func (s *Session) Pop(key string) interface{}

Pop gets data from session then delete it

func (*Session) PopBool added in v0.5.0

func (s *Session) PopBool(key string) bool

PopBool pops bool from session

func (*Session) PopFloat32 added in v0.5.0

func (s *Session) PopFloat32(key string) float32

PopFloat32 pops float32 from session

func (*Session) PopFloat64 added in v0.5.0

func (s *Session) PopFloat64(key string) float64

PopFloat64 pops float64 from session

func (*Session) PopInt added in v0.5.0

func (s *Session) PopInt(key string) int

PopInt pops int from session

func (*Session) PopInt64 added in v0.5.0

func (s *Session) PopInt64(key string) int64

PopInt64 pops int64 from session

func (*Session) PopString added in v0.5.0

func (s *Session) PopString(key string) string

PopString pops string from session

func (*Session) Regenerate added in v0.5.0

func (s *Session) Regenerate()

Regenerate regenerates session id use when change user access level to prevent session fixation

can not use regenerate and destroy same time Regenerate can call only one time

func (*Session) Renew added in v0.3.2

func (s *Session) Renew()

Renew clear all data in current session and regenerate session id

func (*Session) Set

func (s *Session) Set(key string, value interface{})

Set sets data to session

type Store

type Store interface {
	Get(key string, opt StoreOption) (Data, error)
	Set(key string, value Data, opt StoreOption) error
	Del(key string, opt StoreOption) error
}

Store interface

type StoreOption added in v0.5.0

type StoreOption struct {
	Rolling bool
	TTL     time.Duration
}

StoreOption type

Directories

Path Synopsis
store

Jump to

Keyboard shortcuts

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