shop.tonybtw.com

shop.tonybtw.com

https://git.tonybtw.com/shop.tonybtw.com.git git://git.tonybtw.com/shop.tonybtw.com.git
865 bytes raw
1
package lib
2
3
import (
4
	"crypto/rand"
5
	"encoding/base64"
6
	"net/http"
7
)
8
9
const session_cookie_name = "shop_session"
10
11
func Get_Session_ID(r *http.Request) string {
12
	cookie, err := r.Cookie(session_cookie_name)
13
	if err != nil {
14
		return ""
15
	}
16
	return cookie.Value
17
}
18
19
func Set_Session_ID(w http.ResponseWriter, session_id string) {
20
	http.SetCookie(w, &http.Cookie{
21
		Name:     session_cookie_name,
22
		Value:    session_id,
23
		Path:     "/",
24
		HttpOnly: true,
25
		SameSite: http.SameSiteLaxMode,
26
		MaxAge:   86400 * 7,
27
	})
28
}
29
30
func Generate_Session_ID() string {
31
	b := make([]byte, 32)
32
	rand.Read(b)
33
	return base64.URLEncoding.EncodeToString(b)
34
}
35
36
func Get_Or_Create_Session_ID(w http.ResponseWriter, r *http.Request) string {
37
	session_id := Get_Session_ID(r)
38
	if session_id == "" {
39
		session_id = Generate_Session_ID()
40
		Set_Session_ID(w, session_id)
41
	}
42
	return session_id
43
}