-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommander.go
116 lines (93 loc) · 2.43 KB
/
commander.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
package kece
import (
"bytes"
"errors"
"sync"
)
var (
commands = map[string]string{
"AUTH": "\x41\x55\x54\x48",
"SET": "\x53\x45\x54",
"GET": "\x47\x45\x54",
"DEL": "\x44\x45\x4C",
"PUBLISH": "\x50\x55\x42\x4C\x49\x53\x48",
}
replies = map[string]string{
"OK": "+OK\x0D\x0A",
"ERROR": "-ERROR\x0D\x0A",
}
crlf = "\x0D\x0A"
lock = &sync.Mutex{}
)
// Commander interface
type Commander interface {
Auth(command, key, value []byte) error
Set(command, key, value []byte) (*Schema, error)
Get(command, key []byte) (*Schema, error)
Delete(command, key []byte) error
Publish(topic string, command, value []byte) ([]byte, error)
}
// NewCommander function, Commander's constructor
func NewCommander(dataStorage DataStructure) Commander {
return &commander{ds: dataStorage}
}
type commander struct {
ds DataStructure
}
// Auth will set auth to kece server
func (c *commander) Auth(command, key, value []byte) error {
lock.Lock()
defer lock.Unlock()
_, ok := commands[string(command)]
if !ok {
return errors.New(ErrorInvalidCommand)
}
// remove line feed and carriage return (13/10)/ CR/LF
key = bytes.Trim(key, crlf)
value = bytes.Trim(value, crlf)
c.ds.Insert(key, value)
return nil
}
// Set will set value to db
func (c *commander) Set(command, key, value []byte) (*Schema, error) {
lock.Lock()
defer lock.Unlock()
_, ok := commands[string(command)]
if !ok {
return nil, errors.New(ErrorInvalidCommand)
}
// remove line feed and carriage return (13/10)/ CR/LF
key = bytes.Trim(key, crlf)
value = bytes.Trim(value, crlf)
newData := c.ds.Insert(key, value)
return newData, nil
}
// Get will get value from db
func (c *commander) Get(command, key []byte) (*Schema, error) {
lock.Lock()
defer lock.Unlock()
_, ok := commands[string(command)]
if !ok {
return nil, errors.New(ErrorInvalidCommand)
}
// remove line feed and carriage return (13/10)/ CR/LF
key = bytes.Trim(key, crlf)
return c.ds.Search(key)
}
// Delete will get value from db
func (c *commander) Delete(command, key []byte) error {
lock.Lock()
defer lock.Unlock()
_, ok := commands[string(command)]
if !ok {
return errors.New(ErrorInvalidCommand)
}
// remove line feed and carriage return (13/10)/ CR/LF
key = bytes.Trim(key, crlf)
return c.ds.Delete(key)
}
// Publish will publish message to specific topic
//TODO
func (c *commander) Publish(topic string, command, value []byte) ([]byte, error) {
return nil, nil
}