会话管理(Session)

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

    如果您正在使用 pongo2 作为应用的模板引擎,则需要对 HTML 进行如下修改:

    1. <!-- templates/signup.tmpl -->
    2. <h2>{{Flash.SuccessMsg}}</h2>
    3. <h2>{{Flash.ErrorMsg}}</h2>
    4. <h2>{{Flash.InfoMsg}}</h2>
    5. <h2>{{Flash.WarningMsg}}</h2>

    将 Flash 输出到当前响应

    默认情况下,Flash 的数据只会在相对应会话的下一个响应中使用,但函数 SuccessErrorInfoWarning 均接受第二个参数来指示是否在当前响应输出数据:

    1. // ...
    2. f.Success("yes!!!", true)
    3. f.Error("opps...", true)
    4. f.Info("aha?!", true)
    5. f.Warning("Just be careful.", true)
    6. // ...

    该服务允许接受一个参数来进行自定义选项(session.Options):

    1. //...
    2. m.Use(session.Sessioner(session.Options{
    3. // 提供器的名称,默认为 "memory"
    4. // 提供器的配置,根据提供器而不同
    5. ProviderConfig: "",
    6. // 用于存放会话 ID 的 Cookie 名称,默认为 "MacaronSession"
    7. CookieName: "MacaronSession",
    8. // Cookie 储存路径,默认为 "/"
    9. CookiePath: "/",
    10. // GC 执行时间间隔,默认为 3600 秒
    11. Gclifetime: 3600,
    12. // 最大生存时间,默认和 GC 执行时间间隔相同
    13. // 仅限使用 HTTPS,默认为 false
    14. Secure: false,
    15. // Cookie 生存时间,默认为 0 秒
    16. CookieLifeTime: 0,
    17. // Cookie 储存域名,默认为空
    18. Domain: "",
    19. // 会话 ID 长度,默认为 16 位
    20. IDLength: 16,
    21. // 配置分区名称,默认为 "session"
    22. Section: "session",
    23. }))
    24. //...

    目前有 9 款内置的提供器,除了 内存文件 提供器外,您都必须显式导入其它提供器的驱动。

    内存

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

    Redis

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

    Memcache

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

    可以使用以下 SQL 语句创建数据库(请确保 key 的长度和您设置的 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. );
    1. import _ "github.com/go-macaron/session/postgres"
    2. //...
    3. m.Use(session.Sessioner(session.Options{
    4. Provider: "postgres",
    5. ProviderConfig: "user=a password=b dbname=c sslmode=disable",
    6. }))
    7. //...

    MySQL

    可以使用以下 SQL 语句创建数据库:

    1. import _ "github.com/go-macaron/session/mysql"
    2. m.Use(session.Sessioner(session.Options{
    3. Provider: "mysql",
    4. ProviderConfig: "username:password@protocol(address)/dbname?param=value",
    5. //...

    Couchbase

    1. import _ "github.com/go-macaron/session/couchbase"
    2. //...
    3. m.Use(session.Sessioner(session.Options{
    4. Provider: "couchbase",
    5. ProviderConfig: "username:password@protocol(address)/dbname?param=value",
    6. }))
    7. //...
    1. import _ "github.com/go-macaron/session/ledis"
    2. //...
    3. m.Use(session.Sessioner(session.Options{
    4. Provider: "ledis",
    5. ProviderConfig: "data_dir=./app.db,db=0",
    6. }))
    7. //...

    Nodb

    1. import _ "github.com/go-macaron/session/nodb"
    2. //...
    3. m.Use(session.Sessioner(session.Options{
    4. Provider: "nodb",
    5. ProviderConfig: "data/cache.db",
    6. }))
    7. //...
    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. // Provider is the interface that provides session manipulations.
    17. type Provider interface {
    18. // Init initializes session provider.
    19. Init(gclifetime int64, config string) error
    20. // Read returns raw session store by session ID.
    21. Read(sid string) (RawStore, error)
    22. // Exist returns true if session with given ID exists.
    23. Exist(sid string) bool
    24. // Destory deletes a session by session ID.
    25. Destory(sid string) error
    26. // Regenerate regenerates a session store from old session ID to new one.
    27. Regenerate(oldsid, sid string) (RawStore, error)
    28. // Count counts and returns number of sessions.
    29. Count() int
    30. // GC calls GC to clean expired sessions.
    31. GC()
    32. }