Go Revel - Session / Flash(會話與flash)
##Session / Flash 作用域
revel提供了兩種cookies存儲機制:
// 一個加密簽過的cookie (限制為4kb).
// 限制: Key 中不能有冒號
type Session map[string]string
// Flash代表只作用于每個請求的cookie,屬于瞬時消息
// 它允許存儲只跨越一個頁面的數據,是臨時性的
// 通常被用于存儲并顯示 執行成功 或 錯誤消息
// 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的會話是指一個字符串map,被存儲為加密簽名的cookies。
有幾點需要注意:
1、4kb限制
2、所有數據被序列化為字符串
3、所有數據可以被用戶看到(未加密),并可以被安全的修改
##Flash
`Flash`提供一次性字符串存儲。
它可以在`Post/Redirect/Get`請求的頁面上一次性的顯示“操作成功!”或“操作失敗!”消息。
示例:
// Show the Settings form
func (c App) ShowSettings() revel.Result {
return c.Render()
}
// Process a post
func (c App) SaveSettings(setting string) revel.Result {
c.Validation.Required(setting)
if c.Validation.HasErrors() {
// 在flash中存儲錯誤提示信息
c.Flash.Error("Settings invalid!")
c.Validation.Keep()
c.FlashParams()
return c.Redirect(App.ShowSettings)
}
saveSetting(setting)
// 在flash中存儲成功提示信息
c.Flash.Success("Settings saved!")
return c.Redirect(App.ShowSettings)
}
上面示例的過程:
1、用戶獲取setting頁面
2、用戶向setting頁面POST數據
3、程序處理用戶提交的數據,并且保存錯誤/成功提示信息到`flash`,然后使用`REDIRECT`重轉向至其他頁面。
這里用到了兩個便利的方法:
1、`Flash.Success(message string)` 是 `Flash.Out["success"] = message`的簡化版
2、`Flash.Error(message string)` 是 `Flash.Out["error"] = message`的簡化版
flash信息可以在模板中使用key來訪問。例如,在模板中使用以下方式來獲取成功/錯誤信息:
{{.flash.success}}
{{.flash.error}}
浙公網安備 33010602011771號