-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
78 lines (67 loc) · 1.35 KB
/
server.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
package server
import (
"fmt"
"github.com/0xlaurens/districache/cache"
"github.com/0xlaurens/districache/proto"
"io"
"log"
"net"
)
type Server struct {
port int
host string
isLeader bool
cache cache.Cacher
}
func NewServer(cache cache.Cacher, settings ...Setting) *Server {
server := &Server{
cache: cache,
host: "127.0.0.1",
port: 3000,
}
for _, setting := range settings {
setting(server)
}
return server
}
func (s *Server) Run() error {
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.host, s.port))
if err != nil {
return fmt.Errorf("listening error %s", err)
}
log.Printf("Server started on (%s:%d)\n", s.host, s.port)
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("Accept error %s\n", err)
continue
}
go s.handleConn(conn)
}
}
func (s *Server) handleConn(conn net.Conn) {
defer func(conn net.Conn) {
_ = conn.Close()
}(conn)
for {
cmd, err := proto.ParseCommand(conn)
if err != nil {
if err == io.EOF {
break
}
log.Println("parse command error:", err)
break
}
go s.handleCommand(conn, cmd)
}
}
func (s *Server) handleCommand(conn net.Conn, cmd any) {
switch v := cmd.(type) {
case *proto.CommandSet:
_ = s.handleSetCommand(conn, v)
case *proto.CommandGet:
_ = s.handleGetCommand(conn, v)
case *proto.CommandDelete:
_ = s.handleDeleteCommand(conn, v)
}
}