stacksession

package
v6.0.2+incompatible Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2015 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package stacksession provides wrappers based on the github.com/gorilla/sessions. It assumes one session per request. If you need multiple sessions pre request, define your own wrapper or use gorilla/sessions directly.

stacksession expects the ResponseWriter to a wrap.Contexter supporting sessions.Session and error

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync/atomic"

	"gopkg.in/go-on/sessions.v1"
	"gopkg.in/go-on/stack.v6"
	"gopkg.in/go-on/stack.v6/third-party/stacksession"
)

func printFlashes(ctx stack.Contexter, w http.ResponseWriter, r *http.Request, next http.Handler) {
	var session stacksession.Session
	ctx.Get(&session)
	for _, fl := range session.Flashes() {
		fmt.Printf("Flash: %v\n", fl)
	}
	next.ServeHTTP(w, r)
}

var counter = int64(0)

func setNameAndFlash(ctx stack.Contexter, w http.ResponseWriter, r *http.Request, next http.Handler) {
	atomic.AddInt64(&counter, 1)
	var session stacksession.Session
	ctx.Get(&session)
	session.Values["name"] = r.URL.Query().Get("name")
	if counter == 1 {
		session.AddFlash("Hello, flash messages world!")
	}
	next.ServeHTTP(w, r)
}

func printName(ctx stack.Contexter, w http.ResponseWriter, r *http.Request) {
	var session stacksession.Session
	ctx.Get(&session)
	fmt.Printf("Name: %s\n", session.Values["name"])
}

var store = sessions.NewCookieStore([]byte("something-very-secret"))

func main() {
	s := stack.New().
		UseWithContext(stacksession.SaveAndClear).
		UseWithContext(stacksession.NewStore(store, "my-session-name")).
		UseFuncWithContext(printFlashes).
		UseFuncWithContext(setNameAndFlash).
		WrapFuncWithContext(printName)

	req, _ := http.NewRequest("GET", "/?name=Peter", nil)
	rec := httptest.NewRecorder()
	s.ServeHTTP(rec, req)
	s.ServeHTTP(rec, req)
	s.ServeHTTP(rec, req)

}
Output:

Name: Peter
Flash: Hello, flash messages world!
Name: Peter
Name: Peter

Index

Examples

Constants

This section is empty.

Variables

View Source
var SaveAndClear = saveAndClear{}

SaveAndClear saves the session and clears up any references to the request. it should be used at the beginning of the mw chain (but after the Contexter)

Functions

func NewStore

func NewStore(st sessions.Store, name string) *store

Types

type Session

type Session struct {
	sessions.Session
}

func (*Session) Reclaim

func (s *Session) Reclaim(repl interface{})

Jump to

Keyboard shortcuts

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