name: Flash messages

sort: 6

Flash Messages

Flash messages are not related to Adobe/Macromedia Flash. They are temporary messages between two logic blocks. All flash messages will be cleared after the very next logic block. They are normally used to send notes and error messages. Their use is suited for the Post/Redirect/Get model. For example:

  1. // Display settings message
  2. func (c *MainController) Get() {
  3. flash := beego.ReadFromRequest(&c.Controller)
  4. if n, ok := flash.Data["notice"]; ok {
  5. // Display settings successful
  6. c.TplNames = "set_success.html"
  7. } else if n, ok = flash.Data["error"]; ok {
  8. // Display error messages
  9. c.TplNames = "set_error.html"
  10. } else {
  11. // Display default settings page
  12. this.Data["list"] = GetInfo()
  13. c.TplNames = "setting_list.html"
  14. }
  15. }
  16. // Process settings messages
  17. func (c *MainController) Post() {
  18. flash := beego.NewFlash()
  19. setting := Settings{}
  20. valid := Validation{}
  21. c.ParseForm(&setting)
  22. if b, err := valid.Valid(setting); err != nil {
  23. flash.Error("Settings invalid!")
  24. flash.Store(&c.Controller)
  25. c.Redirect("/setting", 302)
  26. return
  27. } else if b != nil {
  28. flash.Error("validation err!")
  29. flash.Store(&c.Controller)
  30. c.Redirect("/setting", 302)
  31. return
  32. }
  33. saveSetting(setting)
  34. flash.Notice("Settings saved!")
  35. flash.Store(&c.Controller)
  36. c.Redirect("/setting", 302)
  37. }

The logic of the code above is as follows:

  1. Execute GET method. There’s no flash data, so display settings page.
  2. After submission, execute POST and initialize a flash. If checking failed, set error flash message. If checking passed, save settings and set flash message to successful.
  3. Redirect to GET request.
  4. GET request receives flash message and executes the related logic. Show error page or success page based on the type of message.

ReadFromRequest already implemented assigning message to flash by default, so you can use it in your template:

  1. {{.flash.error}}
  2. {{.flash.warning}}
  3. {{.flash.notice}}

There are 3 different levels of flash messages:

  • Notice: Notice message
  • Warning: Warning message
  • Error: Error message