Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Revel Session / Flash


May 15, 2021 Revel


Table of contents


Revel supports two cookie-based storage mechanisms

// 一个签名 cookie (不超过4kb).
// 限制: Keys may not have a colon in them.
type Session map[string]string

// 在每个请求中,Flash 获取并重写cookie。
// 它允许数据每次跨越存储到一个页面。It allows data to be stored across one page at a time.
// 它通常用来实现成功或错误消息。
// 比如: Post/Redirect/Get : http://en.wikipedia.org/wiki/Post/Redirect/Get
type Flash struct {
    Data, Out map[string]string
}

Session

Revel's "session" is a string map that encrypts the signature store.

The impact is as follows:

  • The size does not exceed 4kb.
  • All data is saved as a serialized string.
  • Users can view and modify all data (unencrypted).

The default expiration time for session cookies is browser shutdown. Y ou can modify the session.expires configuration at app.config to specify an expiration time. T he format is time. ParseDuration .

Flash

Flash supports the use of string storage alone. This is useful for implementing Post/Redirect/Get mode, or temporarily displaying the "Operation succeeded!" or "Operation failed!" message.

Here's an example:

// 一个设置页面
func (c App) ShowSettings() revel.Result {
    return c.Render()
}

// 处理页面提交数据
func (c App) SaveSettings(setting string) revel.Result {
    // 验证用户输入
    c.Validation.Required(setting)
    if c.Validation.HasErrors() {
        // 设置被带回的flash cookie错误信息
        c.Flash.Error("Settings invalid!")
        // 在flash cookie中保存验证错误
        c.Validation.Keep()
        // 复制所有给定的参数(URL, Form, Multipart)到flash cookie
        c.FlashParams()
        return c.Redirect(App.ShowSettings)
    }
    saveSetting(setting)
    // 设置flash cookie成功消息
    c.Flash.Success("Settings saved!")
    return c.Redirect(App.ShowSettings)
}

The main functions of the example are as follows:

  1. The user gets the settings page.
  2. The user submits a form (POST).
  3. The application processes user requests, saves an error or successful message to flash, and then redirects the Settings page (REDIRECT).
  4. The user gets the settings page to display the message in the flash. (GET)

Two main functions are used:

  1. Flash.Success(message string) a short-form way of Flash.Out["success"] = message and message
  2. Flash.Error(message string) is a short story of Flash.Out["error"] = message

Use keys in templates to get Flash messages. For example, get success and error messages through short-case functions:

{{.flash.success}}
{{.flash.error}}