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。