-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
106 lines (90 loc) · 1.58 KB
/
main.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
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
"strings"
"github.com/bergusman/rediscli-go/resp"
)
func run(host string) {
conn, err := net.Dial("tcp", host)
if err != nil {
log.Fatal(conn)
}
prompt := conn.RemoteAddr().String()
cmds := bufio.NewReader(os.Stdin)
dec := resp.NewDecoder(conn)
for {
fmt.Print(prompt + "> ")
cmd, err := cmds.ReadString('\n')
if err != nil {
log.Fatal(err)
}
if cmd == "exit\n" {
os.Exit(0)
}
_, err = conn.Write([]byte(cmd))
if err != nil {
log.Fatal(err)
}
res, err := dec.Decode()
if err != nil {
log.Fatal(err)
}
print(res)
switch v := res.(type) {
case []interface{}:
if len(v) > 0 {
if vv, ok := v[0].([]byte); ok && string(vv) == "subscribe" {
fmt.Println("Reading messages... (press Ctrl-C to quit)")
for {
res, err := dec.Decode()
if err != nil {
log.Fatal(err)
}
print(res)
}
}
}
}
}
}
func RESPString(v interface{}) string {
w := &strings.Builder{}
var write func(v interface{})
write = func(v interface{}) {
switch v := v.(type) {
default:
fmt.Fprint(w, v)
case nil:
w.WriteString("nil")
case string:
fmt.Fprintf(w, "%q", v)
case []byte:
fmt.Fprintf(w, "%q", v)
case []interface{}:
w.WriteString("[")
for i, vv := range v {
write(vv)
if i != len(v)-1 {
w.WriteString(" ")
}
}
w.WriteString("]")
}
}
write(v)
return w.String()
}
func print(v interface{}) {
fmt.Println(RESPString(v))
}
func main() {
host := ":6379"
if len(os.Args) > 1 {
host = os.Args[1]
}
run(host)
}