Session

未匹配的标注

HTTP会话是非持久性的,在浏览器关闭时会被销毁(在默认浏览器配置中)。它可用于存储Flash消息或任何临时的用户特定数据。如果需要更持久的客户端存储,请使用cookie
Session可直接从buffalo.Context处理程序内部获得。

func MyHandler(c buffalo.Context) error {
  s := c.Session()
}

Session类型

buffalo.Session类型包含在请求期间使用会话所需的所有内容。Buffalo使用github.com/gorilla/sessions包来管理会话。

type Session
  // Clear a session of all values
  func (s *Session) Clear()
  // Delete a specific value from the session
  func (s *Session) Delete(name interface{})
  // Get a value from the session
  func (s *Session) Get(name interface{}) interface{}
  // GetOnce gets a value from the current session and then deletes it.
  func (s *Session) GetOnce(name interface{}) interface{}
  // Save a session
  func (s *Session) Save() error
  // Set a value on the session
  func (s *Session) Set(name, value interface{})

Session存储

默认情况下,Buffalo将使用sessions.CookieStore存储session。
使用SessionStore选项可以改变设置。

app = buffalo.New(buffalo.Options{
  Env:         ENV,
  SessionName: "_coke_session",
  SessionStore: sessions.NewCookieStore([]byte("some session secret")),
})

环境变量SESSION_SECRET 应该在应用启动之前设置。如果未设置,将在日志中看到警告会话未受到保护。
有关详细信息,请参阅文档buffalo.Options

存储复杂类型

正常情况下没有很好的做法存储复杂类型的会话。这有很多原因,但建议存储类型的ID,而不是完整的值。
如果您需要存储复杂类型,就需要在encoding/gob包中注册。

import "encoding/gob"

func init() {
  gob.Register(&models.Person{})
}

保存会话

Buffalo会自动为我们保存会话,因此我们不必做什么。如果保存会话时出错,Buffalo将通过正常的错误处理过程返回错误。

无会话API

构建API服务器时,默认的cookie会话是不需要的。将会话存储设置为sessions.Null就可以了。

app = buffalo.New(buffalo.Options{
  Env:          ENV,
  SessionStore: sessions.Null{},
  SessionName: "_coke_session",
})

如果使用buffalo new创建应用的时候,使用了--api标志,默认会话将设置为sessions.Null。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
superwen
讨论数量: 0
发起讨论 只看当前版本


暂无话题~