/
manager.go
91 lines (73 loc) · 1.83 KB
/
manager.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package session
import (
"net/http"
"sync"
)
var sessions = map[string]*Session{
// Global session
"": &Session{
Cookies: make(map[string]*http.Cookie, 0),
Variables: make(map[string]string),
},
}
var sessionMutex = &sync.Mutex{}
// Get a session based on a URL.
func Get(host string) *Session {
session := ensureSession(host)
if host != "" {
mergedSession := mergeSessions(sessions[""], session)
mergedSession.Host = host
return mergedSession
}
return session
}
// SetCookie sets a cookie into a session, creating one if it doesn't exist
func SetCookie(host string, cookie *http.Cookie) {
ensureSession(host).Cookies[cookie.Name] = cookie
}
// SetGlobalVariable sets a value that will be merged into all sessions
func SetGlobalVariable(name, value string) {
if value == "" {
delete(sessions[""].Variables, name)
return
}
sessions[""].Variables[name] = value
}
// SetVariable sets a value to a specific variable, creating a session if it doesn't exists
func SetVariable(host, name, value string) {
session := ensureSession(host)
if value == "" {
delete(session.Variables, name)
return
}
session.Variables[name] = value
}
func ensureSession(host string) *Session {
sessionMutex.Lock()
defer sessionMutex.Unlock()
session, exists := sessions[host]
if !exists {
session = &Session{
Cookies: make(map[string]*http.Cookie, 0),
Host: host,
Variables: make(map[string]string),
}
sessions[host] = session
}
return session
}
func mergeSessions(sessions ...*Session) *Session {
finalSession := &Session{
Cookies: make(map[string]*http.Cookie, 0),
Variables: make(map[string]string),
}
for _, session := range sessions {
for n, v := range session.Cookies {
finalSession.Cookies[n] = v
}
for n, v := range session.Variables {
finalSession.Variables[n] = v
}
}
return finalSession
}