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 的縮寫

 

至此完成.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM