/
session.go
75 lines (63 loc) · 1.34 KB
/
session.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
package utils
import (
"time"
"sync"
)
var SessionStorage SessionManager
var mutex = new(sync.RWMutex)
func init() {
SessionStorage.new()
}
// use jwt string as session key,
// store user information(username and password) in Session.
type SessionManager struct {
sessions map[string]Session
}
type Session struct {
expire int64
Value interface{}
}
func (s *Session) isExpired(timeNow int64) bool {
if s.expire < timeNow {
return true
}
return false
}
func (s *SessionManager) new() {
s.sessions = make(map[string]Session)
}
/**
* add a new session to session manager.
* @params:token: token string
* expire: unix time for expire
* password: ssh user password
*/
func (s *SessionManager) Put(key string, expire int64, value interface{}) {
s.gc()
mutex.Lock()
s.sessions[key] = Session{expire: expire, Value: value}
mutex.Unlock()
}
func (s *SessionManager) Get(key string) (sessionData Session, exist bool) {
mutex.RLock()
defer mutex.RUnlock()
session, ok := s.sessions[key]
return session, ok
}
func (s *SessionManager) Delete(key string) {
mutex.Lock()
if _, ok := s.sessions[key]; ok {
delete(s.sessions, key)
}
mutex.Unlock()
}
func (s *SessionManager) gc() {
timeNow := time.Now().Unix()
mutex.Lock()
for key, session := range s.sessions {
if session.isExpired(timeNow) {
delete(s.sessions, key)
}
}
mutex.Unlock()
}