Revel provides two cookie-based storage mechanisms for convenience, Session and Flash.

  1. // A signed cookie, and thus limited to 4kb in size.// Restriction: Keys may not have a colon in them.typeSessionmap[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/GettypeFlashstruct{Data,Outmap[string]string}

NOTE: To set your own cookie, use Controller.SetCookie()

  1. func(cMyController)MyMethod()revel.Result{new_cookie:=&http.Cookie{Name:"foo",Value:"Bar"}c.SetCookie(new_cookie)returnc.Render()}

Session

Revel’s concept of session is a string map, stored as a cryptographically signed cookie.

This has some implications:

  • The size limit is 4kb.
  • All data must be serialized to a string for storage.
  • All data may be viewed by the user as it is not encrypted, but it is safe from modification.
    The default lifetime of the session cookie is the browser lifetime. Thiscan be overriden to a specific amount of time by setting the session.expiresoption in conf/app.conf. The format is that oftime.ParseDuration.
  1. func(cMyController)MyMethod()revel.Result{c.Session["foo"]="bar"c.Session["bar"]=1// Error - value needs to be a stringdelete(c.Session,"abc")// Removed item from sessionreturnc.Render()}

Flash

The Flash provides single-use string storage. It is useful for implementingthe Post/Redirect/Get pattern,or for transient “Operation Successful!” or “Operation Failed!” messages.

Here’s an example of that pattern:

  1. // Show the Settings formfunc(cApp)ShowSettings()revel.Result{returnc.Render()}// Process a postfunc(cApp)SaveSettings(settingstring)revel.Result{// Make sure `setting` is provided and not emptyc.Validation.Required(setting)ifc.Validation.HasErrors(){// Sets the flash parameter `error` which will be sent by a flash cookiec.Flash.Error("Settings invalid!")// Keep the validation error from above by setting a flash cookiec.Validation.Keep()// Copies all given parameters (URL, Form, Multipart) to the flash cookiec.FlashParams()returnc.Redirect(App.ShowSettings)}saveSetting(setting)// Sets the flash cookie to contain a success stringc.Flash.Success("Settings saved!")returnc.Redirect(App.ShowSettings)}

Walking through this example:

  • User fetches the settings page.
  • User posts a setting (POST)
  • Application processes the request, saves an error or success message to the flash, and redirects the user to the settings page (REDIRECT)
  • User fetches the settings page, whose template shows the flashed message. (GET)
    It uses two convenience functions:

  • Flash.Success(message string) is an abbreviation of Flash.Out["success"] = message

  • Flash.Error(message string) is an abbreviation of Flash.Out["error"] = message
    Flash messages may be referenced by key in templates. For example, to accessthe success and error messages set by the convenience functions, use theseexpressions:
  1. {{.flash.success}}
  2. {{.flash.error}}

Here is a second scenario where you want the flash variables returned without using aredirect

  1. func(cController)Submit(InputUserName){Input.Validate(c.Validation);ifc.Validation.HasErrors(){data:=map[string]string{}forkey,vals:=rangec.Params.Values{data[key]=strings.Join(vals,",")}c.RenderArgs["flash"]=data// Display input pagereturnc.RenderTemplate("test.html")}...}
GoDoc Reference
GitHub Labels

原文: https://revel.github.io/manual/sessionflash.html