-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboltdbr.go
138 lines (124 loc) · 2.88 KB
/
boltdbr.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package boltdbr
import (
"errors"
"github.com/boltdb/bolt"
"net"
"net/rpc"
)
var (
ErrParamsEror = errors.New("params error")
ErrBucketNotFound = errors.New("bucket not found")
ErrTokenNotMatch = errors.New("token not match")
)
const (
JsonRPC = iota
HTTP
)
type BoltDBR struct {
DB *bolt.DB
opt Options
}
type Query struct {
Bucket []byte
Key []byte
Value []byte
Token string
}
type Response struct {
Value []byte
Error string
}
type Options struct {
Address string
Token string
Type int
}
func New(s *BoltDBR, options Options) (*rpc.Server, net.Listener, error) {
s.opt = options
if options.Type == JsonRPC {
srv := rpc.NewServer()
if err := srv.Register(s); err != nil {
return nil, nil, err
}
l, err := net.Listen("tcp", options.Address)
return srv, l, err
}
if options.Type == HTTP {
rpc.RegisterName("BoltDBR", s)
rpc.HandleHTTP()
l, err := net.Listen("tcp", options.Address)
return nil, l, err
}
return nil, nil, ErrBucketNotFound
}
func (s *BoltDBR) checkAuth(q *Query) error {
if s.opt.Token == "" {
return nil
}
if s.opt.Token == q.Token {
return nil
}
return ErrTokenNotMatch
}
func (s *BoltDBR) CreateBucket(q *Query, r *Response) error {
if err := s.checkAuth(q); err != nil {
return err
}
err := s.DB.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(q.Bucket)
return err
})
if err != nil {
r.Error = err.Error()
}
return err
}
func (s *BoltDBR) Get(q *Query, r *Response) error {
if err := s.checkAuth(q); err != nil {
return err
}
err := s.DB.View(func(tx *bolt.Tx) error {
bk := tx.Bucket(q.Bucket)
if bk == nil {
return ErrBucketNotFound
}
r.Value = bk.Get(q.Key)
return nil
})
return err
}
func (s *BoltDBR) Set(q *Query, r *Response) error {
if err := s.checkAuth(q); err != nil {
return err
}
err := s.DB.Update(func(tx *bolt.Tx) error {
bk, err := tx.CreateBucketIfNotExists(q.Bucket)
if err != nil {
return err
}
return bk.Put(q.Key, q.Value)
})
return err
}
func (s *BoltDBR) Delete(q *Query, r *Response) error {
if err := s.checkAuth(q); err != nil {
return err
}
err := s.DB.Update(func(tx *bolt.Tx) error {
bk, err := tx.CreateBucketIfNotExists(q.Bucket)
if err != nil {
return err
}
return bk.Delete(q.Key)
})
return err
}
func (s *BoltDBR) DeleteBucket(q *Query, r *Response) error {
if err := s.checkAuth(q); err != nil {
return err
}
err := s.DB.Update(func(tx *bolt.Tx) error {
return tx.DeleteBucket(q.Bucket)
})
return err
}