-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
71 lines (58 loc) · 1.45 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
package ela
import (
"errors"
"github.com/gogather/com"
// "github.com/gogather/com/log"
"path/filepath"
)
type Session struct {
path string
}
func NewSession(path string) Session {
return Session{
path: path,
}
}
func (sess *Session) getSessionObject(sid string) (map[string]interface{}, error) {
fullpath := sess.getPath(sid)
data, err := com.ReadFileByte(fullpath)
if err != nil {
return nil, err
}
to := map[string]interface{}{}
err = com.Decode(data, &to)
return to, err
}
func (sess *Session) saveSession(sid string, object interface{}) error {
fullpath := sess.getPath(sid)
str, err := com.Encode(object)
err = com.WriteFileWithCreatePath(fullpath, string(str))
return err
}
func (sess *Session) Get(sid string, key string) (interface{}, error) {
mapObject, err := sess.getSessionObject(sid)
if err != nil {
return nil, err
}
value, ok := mapObject[key]
if ok {
return value, nil
} else {
return nil, errors.New("key value does not exist")
}
}
func (sess *Session) Set(sid string, key string, value interface{}) error {
mapObject, _ := sess.getSessionObject(sid)
if mapObject == nil {
mapObject = map[string]interface{}{}
}
mapObject[key] = value
return sess.saveSession(sid, mapObject)
}
func (sess *Session) getPath(key string) string {
length := len(key) - 3
dir1 := com.SubString(key, 0, 1)
dir2 := com.SubString(key, 1, 2)
file := com.SubString(key, 3, length)
return filepath.Join(sess.path, dir1, dir2, file)
}