-
Notifications
You must be signed in to change notification settings - Fork 0
/
flash.go
61 lines (43 loc) · 1.36 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
package views
import (
"net/http"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v4"
)
type Flashes map[FlashType][]string
type FlashType string
const (
FlashError FlashType = "error"
FlashWarning FlashType = "warning"
FlashInfo FlashType = "info"
FlashSuccess FlashType = "success"
)
// TODO: Move Secret to ENV
// https://github.com/hay-i/chronologger/issues/35
var SessionStore = sessions.NewCookieStore([]byte("secret"))
func getSession(w http.ResponseWriter, r *http.Request) *sessions.Session {
session, err := SessionStore.Get(r, "my-session")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
panic("No session!")
}
return session
}
func GetFlashes(c echo.Context) Flashes {
session := getSession(c.Response(), c.Request())
defer session.Save(c.Request(), c.Response())
flashMap := make(Flashes)
for _, flashType := range []FlashType{FlashError, FlashWarning, FlashInfo, FlashSuccess} {
flashMessages := []string{}
for _, flash := range session.Flashes(string(flashType)) {
flashMessages = append(flashMessages, flash.(string))
}
flashMap[flashType] = flashMessages
}
return flashMap
}
func AddFlash(c echo.Context, message string, flashType FlashType) {
session := getSession(c.Response(), c.Request())
session.AddFlash(message, string(flashType))
session.Save(c.Request(), c.Response())
}