-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
87 lines (74 loc) · 1.34 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
79
80
81
82
83
84
85
86
87
package mc
import (
"encoding/gob"
"errors"
"fmt"
"log"
"net"
"net/rpc"
)
var (
ErrNotFound = errors.New("cache not found")
)
type Error string
type Result struct {
Value []byte
Error Error
}
type Arg struct {
Key string
Value []byte
}
func init() {
gob.Register(Arg{})
gob.Register(Result{})
}
type cache struct {
c Cache
}
func (c *cache) Get(arg *Arg, res *Result) error {
v, ok := c.c.Get(arg.Key)
if !ok {
res.Error = Error("nil")
return nil
}
res.Value = v.([]byte)
return nil
}
func (c *cache) Add(arg *Arg, res *Result) error {
c.c.Add(arg.Key, arg.Value)
res.Value = arg.Value
return nil
}
func (c *cache) Remove(arg *Arg, res *Result) error {
c.c.Remove(arg.Key)
return nil
}
type RPCServer struct {
opt *Option
}
func NewRPCServer(opts ...OptionFunc) *RPCServer {
s := &RPCServer{opt: &Option{}}
for _, o := range opts {
o(s.opt)
}
return s
}
func (s *RPCServer) Run(addr string) {
c := cache{c: s.opt.cache}
rpc.RegisterName("mc", &c) // nolint: errcheck
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("net listen: %s", err)
}
log.Printf("serving on %s\n", addr)
for {
conn, err := l.Accept()
fmt.Printf("%s -> %s\n", conn.RemoteAddr().String(), conn.RemoteAddr().Network())
if err != nil {
log.Printf("accept: %s, skipped", err)
continue
}
go rpc.ServeConn(conn)
}
}