-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsessions.go
56 lines (50 loc) · 1.46 KB
/
sessions.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
// -----------------------------------------------------------------------------
// ZR Library - Web Package zr-web/[session.go]
// (c) [email protected] License: MIT
// -----------------------------------------------------------------------------
package web
import (
"net/http"
"strings"
"sync"
"github.com/balacode/zr"
)
// Sessions _ _
type Sessions struct {
m map[string]*Session
mutex sync.Mutex
} // Sessions
// GetByCookie _ _
func (ob *Sessions) GetByCookie(
w http.ResponseWriter,
req *http.Request,
) *Session {
ob.mutex.Lock()
defer ob.mutex.Unlock()
//
const CookieName = "app_session_id"
// if session cookie already exists, use its session ID..
var id string
cookie, err := req.Cookie(CookieName)
if err == nil {
id = cookie.Value
} else {
// ..if not, create new session ID and save it in a cookie
id = strings.ReplaceAll(zr.UUID(), "-", "")
http.SetCookie(w, &http.Cookie{Name: CookieName, Value: id})
}
// if session is already stored, return pointer to stored session
ptr, exists := ob.m[id]
if exists {
return ptr
}
// if not, add a new Session to the map
ses := Session{id: id, m: map[string]string{}}
ptr = &ses
if ob.m == nil {
ob.m = make(map[string]*Session, 0)
}
ob.m[id] = ptr
return ptr
} // GetByCookie
// end