-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproto.go
94 lines (75 loc) · 1.61 KB
/
proto.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
package main
import (
"bytes"
"fmt"
"io"
"log"
"github.com/tidwall/resp"
)
const (
CommandSET = "SET"
CommandGET = "GET"
CommandHELLO = "HELLO"
)
type Command interface {
}
type SetCommand struct {
key, val []byte
}
type HelloCommand struct {
value string
}
type GetCommand struct {
key []byte
}
func parseCommand(raw string) (Command, error) {
rd := resp.NewReader(bytes.NewBufferString(raw))
for {
v, _, err := rd.ReadValue()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
if v.Type() == resp.Array {
for _, value := range v.Array() {
switch value.String() {
case CommandGET:
if len(v.Array()) != 2 {
return nil, fmt.Errorf("invalid number of variables for GET command")
}
cmd := GetCommand{
key: v.Array()[1].Bytes(),
}
return cmd, nil
case CommandSET:
if len(v.Array()) != 3 {
return nil, fmt.Errorf("invalid number of variables for SET command")
}
cmd := SetCommand{
key: v.Array()[1].Bytes(),
val: v.Array()[2].Bytes(),
}
return cmd, nil
case CommandHELLO:
cmd := HelloCommand{
value: v.Array()[1].String(),
}
return cmd, nil
}
}
}
return nil, fmt.Errorf("invalid or unknown command received: %s", raw)
}
return nil, fmt.Errorf("invalid or unknown command received: %s", raw)
}
func respWriteMap(m map[string]string) string {
buf := bytes.Buffer{}
buf.WriteString("%" + fmt.Sprintf("%d\r\n", len(m)))
for k, v := range m {
buf.WriteString(fmt.Sprintf("+%s\r\n", k))
buf.WriteString(fmt.Sprintf(":%s\r\n", v))
}
return buf.String()
}