Session
Middleware session provides session management for Macaron Instances.

Installation

1
go get github.com/go-macaron/session
Copied!

Usage

1
import (
2
"github.com/go-macaron/session"
3
"gopkg.in/macaron.v1"
4
)
5
6
func main() {
7
m := macaron.Classic()
8
m.Use(macaron.Renderer())
9
m.Use(session.Sessioner())
10
11
m.Get("/", func(sess session.Store) string {
12
sess.Set("session", "session middleware")
13
return sess.Get("session").(string)
14
})
15
16
m.Get("/signup", func(ctx *macaron.Context, f *session.Flash) {
17
f.Success("yes!!!")
18
f.Error("opps...")
19
f.Info("aha?!")
20
f.Warning("Just be careful.")
21
ctx.HTML(200, "signup")
22
})
23
24
m.Run()
25
}
Copied!
1
<!-- templates/signup.tmpl -->
2
<h2>{{.Flash.SuccessMsg}}</h2>
3
<h2>{{.Flash.ErrorMsg}}</h2>
4
<h2>{{.Flash.InfoMsg}}</h2>
5
<h2>{{.Flash.WarningMsg}}</h2>
Copied!

Pongo2

If you're using pongo2 as template engine, you will use flash in HTML as follows:
1
<!-- templates/signup.tmpl -->
2
<h2>{{Flash.SuccessMsg}}</h2>
3
<h2>{{Flash.ErrorMsg}}</h2>
4
<h2>{{Flash.InfoMsg}}</h2>
5
<h2>{{Flash.WarningMsg}}</h2>
Copied!

Output flash in current response

By default, flash will be only used for the next coming response corresponding to the session, but functions Success, Error, Info and Warning are all accept a second argument to indicate whether output flash in current response or not.
1
// ...
2
f.Success("yes!!!", true)
3
f.Error("opps...", true)
4
f.Info("aha?!", true)
5
f.Warning("Just be careful.", true)
6
// ...
Copied!
But remember, flash can only be used once no matter which way you use.

Options

session.Sessioner comes with a variety of configuration options(session.Options):
1
//...
2
m.Use(session.Sessioner(session.Options{
3
// Name of provider. Default is "memory".
4
Provider: "memory",
5
// Provider configuration, it's corresponding to provider.
6
ProviderConfig: "",
7
// Cookie name to save session ID. Default is "MacaronSession".
8
CookieName: "MacaronSession",
9
// Cookie path to store. Default is "/".
10
CookiePath: "/",
11
// GC interval time in seconds. Default is 3600.
12
Gclifetime: 3600,
13
// Max life time in seconds. Default is whatever GC interval time is.
14
Maxlifetime: 3600,
15
// Use HTTPS only. Default is false.
16
Secure: false,
17
// Cookie life time. Default is 0.
18
CookieLifeTime: 0,
19
// Cookie domain name. Default is empty.
20
Domain: "",
21
// Session ID length. Default is 16.
22
IDLength: 16,
23
// Configuration section name. Default is "session".
24
Section: "session",
25
}))
26
//...
Copied!

Providers

There are 9 built-in implementations of session provider, you have to import provider driver explicitly except for memory and file providers.
Following are some basic usage examples for providers.

Memory

1
//...
2
m.Use(session.Sessioner())
3
//...
Copied!

File

1
//...
2
m.Use(session.Sessioner(session.Options{
3
Provider: "file",
4
ProviderConfig: "data/sessions",
5
}))
6
//...
Copied!

Redis

1
import _ "github.com/go-macaron/session/redis"
2
3
//...
4
m.Use(session.Sessioner(session.Options{
5
Provider: "redis",
6
// e.g.: network=tcp,addr=127.0.0.1:6379,password=macaron,db=0,pool_size=100,idle_timeout=180,prefix=session:
7
ProviderConfig: "addr=127.0.0.1:6379,password=macaron",
8
}))
9
//...
Copied!

Memcache

1
import _ "github.com/go-macaron/session/memcache"
2
3
//...
4
m.Use(session.Sessioner(session.Options{
5
Provider: "memcache",
6
// e.g.: 127.0.0.1:9090;127.0.0.1:9091
7
ProviderConfig: "127.0.0.1:9090",
8
}))
9
//...
Copied!

PostgreSQL

Use following SQL to create database(make sure key length matches your Options.IDLength):
1
CREATE TABLE session (
2
key CHAR(16) NOT NULL,
3
data BYTEA,
4
expiry INTEGER NOT NULL,
5
PRIMARY KEY (key)
6
);
Copied!
1
import _ "github.com/go-macaron/session/postgres"
2
3
//...
4
m.Use(session.Sessioner(session.Options{
5
Provider: "postgres",
6
ProviderConfig: "user=a password=b host=localhost port=5432 dbname=c sslmode=disable",
7
}))
8
//...
Copied!

MySQL

Use following SQL to create database:
1
CREATE TABLE `session` (
2
`key` CHAR(16) NOT NULL,
3
`data` BLOB,
4
`expiry` INT(11) UNSIGNED NOT NULL,
5
PRIMARY KEY (`key`)
6
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Copied!
1
import _ "github.com/go-macaron/session/mysql"
2
3
//...
4
m.Use(session.Sessioner(session.Options{
5
Provider: "mysql",
6
ProviderConfig: "username:[email protected](address)/dbname?param=value",
7
}))
8
//...
Copied!

Couchbase

1
import _ "github.com/go-macaron/session/couchbase"
2
3
//...
4
m.Use(session.Sessioner(session.Options{
5
Provider: "couchbase",
6
ProviderConfig: "username:[email protected](address)/dbname?param=value",
7
}))
8
//...
Copied!

Ledis

1
import _ "github.com/go-macaron/session/ledis"
2
3
//...
4
m.Use(session.Sessioner(session.Options{
5
Provider: "ledis",
6
ProviderConfig: "data_dir=./app.db,db=0",
7
}))
8
//...
Copied!

Nodb

1
import _ "github.com/go-macaron/session/nodb"
2
3
//...
4
m.Use(session.Sessioner(session.Options{
5
Provider: "nodb",
6
ProviderConfig: "data/cache.db",
7
}))
8
//...
Copied!

Implement Provider Interface

In case you need to have your own implementation of session storage and provider, you can implement following two interfaces and take memory provider as a study example.
1
// RawStore is the interface that operates the session data.
2
type RawStore interface {
3
// Set sets value to given key in session.
4
Set(key, value interface{}) error
5
// Get gets value by given key in session.
6
Get(key interface{}) interface{}
7
// Delete deletes a key from session.
8
Delete(key interface{}) error
9
// ID returns current session ID.
10
ID() string
11
// Release releases session resource and save data to provider.
12
Release() error
13
// Flush deletes all session data.
14
Flush() error
15
}
16
17
// Provider is the interface that provides session manipulations.
18
type Provider interface {
19
// Init initializes session provider.
20
Init(gclifetime int64, config string) error
21
// Read returns raw session store by session ID.
22
Read(sid string) (RawStore, error)
23
// Exist returns true if session with given ID exists.
24
Exist(sid string) bool
25
// Destory deletes a session by session ID.
26
Destory(sid string) error
27
// Regenerate regenerates a session store from old session ID to new one.
28
Regenerate(oldsid, sid string) (RawStore, error)
29
// Count counts and returns number of sessions.
30
Count() int
31
// GC calls GC to clean expired sessions.
32
GC()
33
}
Copied!
Last modified 2yr ago