-
-
Notifications
You must be signed in to change notification settings - Fork 945
/
storage.go
82 lines (73 loc) · 1.75 KB
/
storage.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
package openwechat
import (
"io"
"os"
"sync"
)
type HotReloadStorageItem struct {
Jar *Jar
BaseRequest *BaseRequest
LoginInfo *LoginInfo
WechatDomain WechatDomain
SyncKey *SyncKey
UUID string
}
// HotReloadStorage 热登陆存储接口
type HotReloadStorage io.ReadWriter
// fileHotReloadStorage 实现HotReloadStorage接口
// 以文件的形式存储
type fileHotReloadStorage struct {
filename string
file *os.File
lock sync.Mutex
}
func (j *fileHotReloadStorage) Read(p []byte) (n int, err error) {
j.lock.Lock()
defer j.lock.Unlock()
if j.file == nil {
j.file, err = os.OpenFile(j.filename, os.O_RDWR, 0600)
if os.IsNotExist(err) {
return 0, ErrInvalidStorage
}
if err != nil {
return 0, err
}
}
return j.file.Read(p)
}
func (j *fileHotReloadStorage) Write(p []byte) (n int, err error) {
j.lock.Lock()
defer j.lock.Unlock()
if j.file == nil {
j.file, err = os.Create(j.filename)
if err != nil {
return 0, err
}
}
// reset offset and truncate file
if _, err = j.file.Seek(0, io.SeekStart); err != nil {
return
}
if err = j.file.Truncate(0); err != nil {
return
}
// json decode only write once
return j.file.Write(p)
}
func (j *fileHotReloadStorage) Close() error {
j.lock.Lock()
defer j.lock.Unlock()
if j.file == nil {
return nil
}
return j.file.Close()
}
// Deprecated: use NewFileHotReloadStorage instead
// 不再单纯以json的格式存储,支持了用户自定义序列化方式
func NewJsonFileHotReloadStorage(filename string) io.ReadWriteCloser {
return NewFileHotReloadStorage(filename)
}
// NewFileHotReloadStorage implements HotReloadStorage
func NewFileHotReloadStorage(filename string) io.ReadWriteCloser {
return &fileHotReloadStorage{filename: filename}
}