forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flash.go
65 lines (57 loc) · 1.5 KB
/
flash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package revel
import (
"fmt"
"net/http"
"net/url"
)
// 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
}
func (f Flash) Error(msg string, args ...interface{}) {
if len(args) == 0 {
f.Out["error"] = msg
} else {
f.Out["error"] = fmt.Sprintf(msg, args...)
}
}
func (f Flash) Success(msg string, args ...interface{}) {
if len(args) == 0 {
f.Out["success"] = msg
} else {
f.Out["success"] = fmt.Sprintf(msg, args...)
}
}
type FlashPlugin struct{ EmptyPlugin }
func (p FlashPlugin) BeforeRequest(c *Controller) {
c.Flash = restoreFlash(c.Request.Request)
c.RenderArgs["flash"] = c.Flash.Data
}
func (p FlashPlugin) AfterRequest(c *Controller) {
// Store the flash.
var flashValue string
for key, value := range c.Flash.Out {
flashValue += "\x00" + key + ":" + value + "\x00"
}
c.SetCookie(&http.Cookie{
Name: CookiePrefix + "_FLASH",
Value: url.QueryEscape(flashValue),
Path: "/",
})
}
// Restore flash from a request.
func restoreFlash(req *http.Request) Flash {
flash := Flash{
Data: make(map[string]string),
Out: make(map[string]string),
}
if cookie, err := req.Cookie(CookiePrefix + "_FLASH"); err == nil {
ParseKeyValueCookie(cookie.Value, func(key, val string) {
flash.Data[key] = val
})
}
return flash
}