-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.go
More file actions
49 lines (47 loc) · 979 Bytes
/
command.go
File metadata and controls
49 lines (47 loc) · 979 Bytes
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
package main
import (
"strconv"
"strings"
)
func handleCommand(c *Client, store *Storage, parts []string) {
cmd := strings.ToUpper(parts[0])
switch cmd {
case "SET":
if !canWrite(c.User) {
c.Conn.Write([]byte("ERR no permission\n"))
return
}
if len(parts) < 3 {
c.Conn.Write([]byte("ERR usage: SET key value [TTL_seconds]\n"))
return
}
ttl := 0
if len(parts) == 4 {
t, err := strconv.Atoi(parts[3])
if err != nil {
c.Conn.Write([]byte("ERR TTL must be integer\n"))
return
}
ttl = t
}
store.Set(parts[1], parts[2], ttl)
c.Conn.Write([]byte("OK\n"))
case "GET":
if !canRead(c.User) {
c.Conn.Write([]byte("ERR no permission\n"))
return
}
if len(parts) != 2 {
c.Conn.Write([]byte("ERR usage: GET key\n"))
return
}
val, ok := store.Get(parts[1])
if !ok {
c.Conn.Write([]byte("(nil)\n"))
return
}
c.Conn.Write([]byte(val + "\n"))
default:
c.Conn.Write([]byte("ERR unknown command\n"))
}
}