cookie.go
1package session
2
3import (
4 "net/http"
5 "time"
6)
7
8const (
9 sessionCookie string = "__Host-session-id"
10 flashCookie string = "app-flashmsg"
11)
12
13// SetCookie sets a secure, HTTP only, and strict cookie with the session identifier
14func SetCookie(w http.ResponseWriter, sessionID string, maxage time.Duration) {
15 http.SetCookie(w, &http.Cookie{
16 Name: sessionCookie,
17 Value: sessionID,
18 MaxAge: int(maxage.Seconds()),
19 Secure: true,
20 HttpOnly: true,
21 Path: "/",
22 SameSite: http.SameSiteStrictMode,
23 })
24}
25
26// ExpireCookie deletes the session cookie from the browser jar
27func ExpireCookie(w http.ResponseWriter) {
28 http.SetCookie(w, &http.Cookie{
29 Name: sessionCookie,
30 MaxAge: -1,
31 Secure: true,
32 HttpOnly: true,
33 Path: "/",
34 SameSite: http.SameSiteStrictMode,
35 })
36}
37
38// GetCookie returns the session identifier or error http.ErrNoCookie if not found
39func GetCookie(r *http.Request) (sessionID string, err error) {
40 c, err := r.Cookie(sessionCookie)
41 if c != nil {
42 sessionID = c.Value
43 }
44 return
45}
46
47// SetFlash sets a flash message in a resopnse cookie readable from javascript. Cookie
48// name is `app-flashmsg`
49func SetFlash(w http.ResponseWriter, msg string) {
50 http.SetCookie(w, &http.Cookie{
51 Name: flashCookie,
52 Value: msg,
53 MaxAge: 0,
54 Secure: true,
55 HttpOnly: false,
56 SameSite: http.SameSiteStrictMode,
57 })
58}