Go Web开发之Revel - Session/Flash

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)
}

我们来看一下这个例子:

  1. 用户加载settings页面
  2. 用户post一个setting
  3. 应用程序处理这个request, 保存一个错误或成功信息到flash并重定向用户到setting页面
  4. 用户加载settings页面,模板将显示flash带来的的信息

它使用两个方便的函数:

  1. Flash.Success(message string) 是 Flash.Out[“success”] = message 的缩写
  2. Flash.Error(message string) 是 Flash.Out[“error”] = message 的缩写

至此完成.