Go Web开发之Revel - Session/Flash
2013-01-06 09:55 Danny.tian 阅读(3313) 评论(2) 收藏 举报Revel提供两个基于cookie的存储机制.
// A signed cookie (and thus limited to 4kb in size).
// Restriction: Keys may not have a colon in them.
type Session map[string]string
// Flash represents a cookie that gets overwritten on each request.
// It allows data to be stored across one page at a time.
// This is commonly used to implement success or error messages.
// e.g. the Post/Redirect/Get pattern: http://en.wikipedia.org/wiki/Post/Redirect/Get
type Flash struct {
Data, Out map[string]string
}
Session
Revel session是一个字符串字典, 存储为加密签名的cookie.
它有下面的暗示:
- 大小不超过4kb
- 全部的数据必须被序列化为一个字符串存储
- 全部的数据可以被用户查看(它没有被编码), but it is safe from modification.
Flash
Flash提供一个单次使用的字符串存储. 它对于实现the Post/Redirect/Get 模式很有帮助,或者用于转换"操作成功!"或"操作失败!"消息.
下面是这个模式的例子:
// Show the Settings form
func (c App) ShowSettings() rev.Result {
return c.Render()
}
// Process a post
func (c App) SaveSettings(setting string) rev.Result {
c.Validation.Required(setting)
if c.Validation.HasErrors() {
c.Flash.Error("Settings invalid!")
c.Validation.Keep()
c.Params.Flash()
return c.Redirect(App.ShowSettings)
}
saveSetting(setting)
c.Flash.Success("Settings saved!")
return c.Redirect(App.ShowSettings)
}
我们来看一下这个例子:
- 用户加载settings页面
- 用户post一个setting
- 应用程序处理这个request, 保存一个错误或成功信息到flash并重定向用户到setting页面
- 用户加载settings页面,模板将显示flash带来的的信息
它使用两个方便的函数:
- Flash.Success(message string) 是 Flash.Out[“success”] = message 的缩写
Flash.Error(message string)是 Flash.Out[“error”] = message 的缩写
至此完成.
浙公网安备 33010602011771号