-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflash.go
More file actions
76 lines (67 loc) · 1.77 KB
/
flash.go
File metadata and controls
76 lines (67 loc) · 1.77 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
package main
import (
"bytes"
"encoding/base64"
"encoding/gob"
"net/http"
)
type FlashAlert string
const (
SuccessFlashAlert FlashAlert = "success"
InfoFlashAlert FlashAlert = "info"
WarningFlashAlert FlashAlert = "warning"
ErrorFlashAlert FlashAlert = "error"
FlashCookieName = "flash"
)
type FlashMessage struct {
Alert FlashAlert
Message string
}
func (inst *httpInstance) setFlashMessage(w http.ResponseWriter, alert FlashAlert, message string) error {
msg := FlashMessage{
Alert: alert,
Message: message,
}
var b bytes.Buffer
errEncode := gob.NewEncoder(&b).Encode(msg)
if errEncode != nil {
inst.logger.Error().Err(errEncode).Msg("Failed to encode flash message")
return errEncode
}
sessionCookie := &http.Cookie{
Name: FlashCookieName,
Value: base64.StdEncoding.EncodeToString(b.Bytes()),
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: inst.useSSL || inst.useAutoSSL,
}
http.SetCookie(w, sessionCookie)
return nil
}
func (inst *httpInstance) getFlashMessage(w http.ResponseWriter, r *http.Request) (*FlashMessage, error) {
cookie, err := r.Cookie(FlashCookieName)
if err != nil {
return nil, err
}
cookieValue, errDecode := base64.StdEncoding.DecodeString(cookie.Value)
if errDecode != nil {
inst.logger.Error().Err(errDecode).Msg("Failed to decode flash message")
return nil, errDecode
}
var msg FlashMessage
errGob := gob.NewDecoder(bytes.NewReader(cookieValue)).Decode(&msg)
if errGob != nil {
inst.logger.Error().Err(errGob).Msg("Failed to decode flash message")
return nil, errGob
}
// Clear the cookie
sessionCookie := &http.Cookie{
Name: FlashCookieName,
Path: "/",
MaxAge: -1,
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, sessionCookie)
return &msg, nil
}