-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeer.go
75 lines (67 loc) · 1.25 KB
/
peer.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
package main
import (
"fmt"
"io"
"log"
"net"
"github.com/tidwall/resp"
)
type Peer struct {
conn net.Conn
msgCh chan Message
delCh chan *Peer
}
func (p *Peer) Send(msg []byte) (int, error) {
return p.conn.Write(msg)
}
func NewPeer(conn net.Conn, msgCh chan Message, delChan chan *Peer) *Peer {
return &Peer{
conn: conn,
msgCh: msgCh,
delCh: delChan,
}
}
func (p *Peer) readLoop() error {
rd := resp.NewReader(p.conn)
for {
v, _, err := rd.ReadValue()
if err == io.EOF {
p.delCh <- p
break
}
if err != nil {
log.Fatal(err)
}
if v.Type() == resp.Array {
for _, val := range v.Array() {
switch val.String() {
case CommandGet:
if len(v.Array()) != 2 {
return fmt.Errorf("invalid number of variables for GET command")
}
cmd := GetCommand{
key: v.Array()[1].Bytes(),
}
// fmt.Println("geot GET cmd", cmd)
p.msgCh <- Message{
cmd: cmd,
peer: p,
}
case CommandSet:
if len(v.Array()) != 3 {
return fmt.Errorf("invalid number of variables for SET command")
}
cmd := SetCommand{
key: v.Array()[1].Bytes(),
val: v.Array()[2].Bytes(),
}
p.msgCh <- Message{
cmd: cmd,
peer: p,
}
}
}
}
}
return nil
}