-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflash.go
More file actions
85 lines (70 loc) · 2.03 KB
/
flash.go
File metadata and controls
85 lines (70 loc) · 2.03 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package httpx
import (
"net/http"
"github.com/gorilla/sessions"
)
type (
FlashType string
Flash struct {
Type FlashType
Message string
}
)
const (
FlashTypeSuccess FlashType = "success"
FlashTypeError FlashType = "error"
FlashTypeInfo FlashType = "info"
FlashTypeWarning FlashType = "warning"
)
var (
FlashStore *sessions.CookieStore
flashTypes = []FlashType{FlashTypeSuccess, FlashTypeError, FlashTypeInfo, FlashTypeWarning}
)
// InitFlashStore initializes the flash message store with secret key
func InitFlashStore(secret []byte) {
FlashStore = sessions.NewCookieStore(secret)
}
// SetFlash adds a flash message
func SetFlash(w http.ResponseWriter, r *http.Request, ftype FlashType, msg string) error {
session, err := FlashStore.Get(r, "flash")
if err != nil {
return err
}
session.AddFlash(msg, string(ftype))
return session.Save(r, w)
}
// GetFlashes retrieves and clears all flash messages
func GetFlashes(w http.ResponseWriter, r *http.Request) ([]Flash, error) {
session, err := FlashStore.Get(r, "flash")
if err != nil {
return nil, err
}
var flashes []Flash
for _, ftype := range flashTypes {
for _, msg := range session.Flashes(string(ftype)) {
if s, ok := msg.(string); ok {
flashes = append(flashes, Flash{Type: ftype, Message: s})
}
}
}
if err := session.Save(r, w); err != nil {
return flashes, err
}
return flashes, nil
}
// FlashSuccess adds a success flash message
func FlashSuccess(w http.ResponseWriter, r *http.Request, msg string) error {
return SetFlash(w, r, FlashTypeSuccess, msg)
}
// FlashError adds an error flash message
func FlashError(w http.ResponseWriter, r *http.Request, msg string) error {
return SetFlash(w, r, FlashTypeError, msg)
}
// FlashInfo adds an info flash message
func FlashInfo(w http.ResponseWriter, r *http.Request, msg string) error {
return SetFlash(w, r, FlashTypeInfo, msg)
}
// FlashWarning adds a warning flash message
func FlashWarning(w http.ResponseWriter, r *http.Request, msg string) error {
return SetFlash(w, r, FlashTypeWarning, msg)
}