-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkvstore.go
83 lines (63 loc) · 1.56 KB
/
kvstore.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
package main
import (
"bufio"
"context"
"flag"
"fmt"
"net"
"strings"
"github.com/mcfdn/kvstore/operations"
"github.com/mcfdn/kvstore/store"
)
func main() {
hostPtr := flag.String("h", "localhost", "The host to listen on")
portPtr := flag.Int("p", 7777, "The port to listen on")
flag.Parse()
router := operations.NewRouter()
operations.RegisterOperations(router)
listen(*hostPtr, *portPtr, router, store.New())
}
func listen(host string, port int, r *operations.Router, s *store.Store) {
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
defer ln.Close()
if err != nil {
panic(err)
}
fmt.Printf("Listening on %s:%d\n", host, port)
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
go handleConnection(conn, r, s)
}
}
func handleConnection(conn net.Conn, r *operations.Router, s *store.Store) {
defer conn.Close()
defer fmt.Println("Client closed connection")
fmt.Println("Client initiated connection")
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
return
}
routeMessage(message, conn, r, s)
}
}
func routeMessage(message string, conn net.Conn, r *operations.Router, s *store.Store) {
args := strings.Fields(message)
if len(args) < 1 {
return
}
ctx := context.WithValue(context.Background(), "args", args[1:])
result, err := r.Route(ctx, s, args[0])
if err != nil {
conn.Write([]byte(fmt.Sprintln(err.Error())))
return
}
if val := result.Value; val != "" {
conn.Write([]byte(fmt.Sprintln(val)))
}
conn.Write([]byte(fmt.Sprintln("OK")))
}