-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (65 loc) · 1.18 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
package main
import (
"bufio"
"fmt"
"io"
"net"
"os"
"strings"
)
func main() {
l, err := net.Listen("tcp", "localhost:6379")
if err != nil {
panic("cannot start the server")
}
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("Error: ", err)
return
}
// for handling concurrent clients
go handleClient(conn)
}
}
func handleClient(conn net.Conn) {
defer func() {
err := conn.Close()
if err != nil {
fmt.Println("Error:", err)
}
}()
for {
r := bufio.NewReader(conn)
resp := NewResp(r)
val, err := resp.Read()
if err != nil {
if err == io.EOF {
break
}
fmt.Println("error reading from client: ", err.Error())
os.Exit(1)
}
if val.typ != "array" {
fmt.Println("Invalid request, expected array")
continue
}
if len(val.array) == 0 {
fmt.Println("Invalid request, expected array length > 0")
continue
}
command := strings.ToUpper(val.array[0].bulk)
args := val.array[1:]
writer := NewWriter(conn)
handler, ok := Handlers[command]
if !ok {
fmt.Println("Invalid command: ", command)
writer.Write(Value{
typ: "string",
str: "",
})
}
result := handler(args)
writer.Write(result)
}
}