This repository has been archived by the owner on Oct 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
mcserver.go
89 lines (76 loc) · 1.86 KB
/
mcserver.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
package main
import (
"io"
"log"
"net"
"time"
"github.com/dustin/gomemcached"
"github.com/dustin/gomemcached/server"
"github.com/dustin/seriesly/timelib"
)
const (
CREATE_BUCKET = gomemcached.CommandCode(0x85)
DELETE_BUCKET = gomemcached.CommandCode(0x86)
LIST_BUCKETS = gomemcached.CommandCode(0x87)
SELECT_BUCKET = gomemcached.CommandCode(0x89)
)
type mcSession struct {
dbname string
}
func (sess *mcSession) HandleMessage(
w io.Writer, req *gomemcached.MCRequest) *gomemcached.MCResponse {
switch req.Opcode {
case SELECT_BUCKET:
log.Printf("Selecting bucket %s", req.Key)
sess.dbname = string(req.Key)
case gomemcached.SETQ, gomemcached.SET:
fk := string(req.Key)
var k string
if fk == "" {
k = time.Now().UTC().Format(time.RFC3339Nano)
} else {
t, err := timelib.ParseTime(fk)
if err != nil {
return &gomemcached.MCResponse{
Status: gomemcached.EINVAL,
Body: []byte("Invalid key"),
}
}
k = t.UTC().Format(time.RFC3339Nano)
}
err := dbstore(sess.dbname, k, req.Body)
if err != nil {
return &gomemcached.MCResponse{
Status: gomemcached.NOT_STORED,
Body: []byte(err.Error()),
}
}
if req.Opcode == gomemcached.SETQ {
return nil
}
case gomemcached.NOOP:
default:
return &gomemcached.MCResponse{Status: gomemcached.UNKNOWN_COMMAND}
}
return &gomemcached.MCResponse{}
}
func waitForMCConnections(ls net.Listener) {
for {
s, e := ls.Accept()
if e == nil {
log.Printf("Got a connection from %s", s.RemoteAddr())
go memcached.HandleIO(s, &mcSession{})
} else {
log.Printf("Error accepting from %s", ls)
}
}
}
func listenMC(bindaddr string) net.Listener {
ls, e := net.Listen("tcp", bindaddr)
if e != nil {
log.Fatalf("Error binding to memcached socket: %s", e)
}
log.Printf("Listening for memcached connections on %v", bindaddr)
go waitForMCConnections(ls)
return ls
}