forked from mmacdo54/go-redis-clone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (59 loc) · 1.26 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
package main
import (
"fmt"
"net"
"github.com/mmacdo54/go-redis-clone/internal/handlers"
"github.com/mmacdo54/go-redis-clone/internal/resp"
"github.com/mmacdo54/go-redis-clone/internal/storage"
)
func main() {
l, err := net.Listen("tcp", ":6379")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Listening for tcp connections on port 6379")
store, err := storage.NewStore("database.aof")
if err != nil {
fmt.Println(err)
return
}
defer store.Close()
store.Read(func(v resp.RespValue) {
if _, err := handlers.HandleRespValue(v, nil); err != nil {
fmt.Println(err)
return
}
})
for {
conn, err := l.Accept()
if err != nil {
fmt.Println(err)
continue
}
go handleConnection(conn, store)
}
}
func handleConnection(conn net.Conn, store *storage.Store) {
defer conn.Close()
for {
reader := resp.NewRespReader(conn)
writer := resp.NewRespWriter(conn)
val, err := reader.ReadResp()
if err != nil {
if err := writer.WriteErrorResp(err); err != nil {
fmt.Println(err)
}
continue
}
response, err := handlers.HandleRespValue(val, &conn)
if err != nil {
if err := writer.WriteErrorResp(err); err != nil {
fmt.Println(err)
}
continue
}
store.Write(val)
writer.WriteResp(response)
}
}