-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
107 lines (90 loc) · 1.91 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
107
package main
import (
"fmt"
"github.com/Mohanbarman/breezedb/aof"
"github.com/Mohanbarman/breezedb/commands"
"github.com/Mohanbarman/breezedb/resp"
"net"
"os"
"strings"
)
func main() {
port := ":6380"
if len(os.Args) > 1 {
port = fmt.Sprintf(":%s", os.Args[1])
}
l, err := net.Listen("tcp", port)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Listening on port", port)
aof, err := aof.NewAof("db.aof")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer aof.Close()
err = aof.Read(func(v resp.Value) {
command := strings.ToUpper(v.Array[0].Bulk)
args := v.Array[1:]
handler, ok := commands.Handlers[command]
options, err := commands.ParseOptions(command, args)
if err != nil {
return
}
if !ok {
return
}
handler(v.Array[1:], options)
})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for {
conn, err := l.Accept()
defer conn.Close()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
go func() {
for {
writer := resp.NewWriter(conn)
_resp := resp.NewResp(conn)
value, err := _resp.Read()
if err != nil {
fmt.Println(err)
return
}
if value.Typ != "array" {
fmt.Println("Invalid request")
continue
}
if len(value.Array) == 0 {
fmt.Println("Invalid request, array is empty")
continue
}
command := strings.ToUpper(value.Array[0].Bulk)
args := value.Array[1:]
commandOptions, err := commands.ParseOptions(command, args)
if err != nil {
writer.Write(resp.Value{Typ: "error", Str: err.Error()})
continue
}
handler, ok := commands.Handlers[command]
if !ok {
fmt.Println("Invalid command ", command)
writer.Write(resp.Value{Typ: "string", Str: ""})
continue
}
result := handler(args, commandOptions)
if command == "SET" || command == "HSET" {
aof.Write(value, commandOptions)
}
writer.Write(result)
}
}()
}
}