Add API Framework Revel Source Files
[iec.git] / src / foundation / api / revel / flash.go
1 // Copyright (c) 2012-2016 The Revel Framework Authors, All rights reserved.
2 // Revel Framework source code and usage is governed by a MIT style
3 // license that can be found in the LICENSE file.
4
5 package revel
6
7 import (
8         "fmt"
9         "net/http"
10         "net/url"
11 )
12
13 // Flash represents a cookie that is overwritten on each request.
14 // It allows data to be stored across one page at a time.
15 // This is commonly used to implement success or error messages.
16 // E.g. the Post/Redirect/Get pattern:
17 // http://en.wikipedia.org/wiki/Post/Redirect/Get
18 type Flash struct {
19         // `Data` is the input which is read in `restoreFlash`, `Out` is the output which is set in a FLASH cookie at the end of the `FlashFilter()`
20         Data, Out map[string]string
21 }
22
23 // Error serializes the given msg and args to an "error" key within
24 // the Flash cookie.
25 func (f Flash) Error(msg string, args ...interface{}) {
26         if len(args) == 0 {
27                 f.Out["error"] = msg
28         } else {
29                 f.Out["error"] = fmt.Sprintf(msg, args...)
30         }
31 }
32
33 // Success serializes the given msg and args to a "success" key within
34 // the Flash cookie.
35 func (f Flash) Success(msg string, args ...interface{}) {
36         if len(args) == 0 {
37                 f.Out["success"] = msg
38         } else {
39                 f.Out["success"] = fmt.Sprintf(msg, args...)
40         }
41 }
42
43 // FlashFilter is a Revel Filter that retrieves and sets the flash cookie.
44 // Within Revel, it is available as a Flash attribute on Controller instances.
45 // The name of the Flash cookie is set as CookiePrefix + "_FLASH".
46 func FlashFilter(c *Controller, fc []Filter) {
47         c.Flash = restoreFlash(c.Request)
48         c.ViewArgs["flash"] = c.Flash.Data
49
50         fc[0](c, fc[1:])
51
52         // Store the flash.
53         var flashValue string
54         for key, value := range c.Flash.Out {
55                 flashValue += "\x00" + key + ":" + value + "\x00"
56         }
57         c.SetCookie(&http.Cookie{
58                 Name:     CookiePrefix + "_FLASH",
59                 Value:    url.QueryEscape(flashValue),
60                 HttpOnly: true,
61                 Secure:   CookieSecure,
62                 Path:     "/",
63         })
64 }
65
66 // restoreFlash deserializes a Flash cookie struct from a request.
67 func restoreFlash(req *Request) Flash {
68         flash := Flash{
69                 Data: make(map[string]string),
70                 Out:  make(map[string]string),
71         }
72         if cookie, err := req.Cookie(CookiePrefix + "_FLASH"); err == nil {
73                 ParseKeyValueCookie(cookie.GetValue(), func(key, val string) {
74                         flash.Data[key] = val
75                 })
76         }
77         return flash
78 }