-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
121 lines (90 loc) · 2.15 KB
/
handler.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import "sync"
var Handlers = map[string]func([]Value) Value{
"PING": ping,
"SET": set,
"GET": get,
"HSET": hset,
"HGET": hget,
"HGETALL": hgetall,
}
func ping(args []Value) Value {
if len(args) == 0 {
return Value{typ: "string", str: "PONG"}
}
return Value{typ: "string", str: args[0].bulk}
}
var SETs = map[string]string{}
var SETsMu = sync.RWMutex{}
func set(args []Value) Value {
if len(args) != 2 {
return Value{typ: "error", str: "ERR wrong number of arguments ofr 'set' command"}
}
key := args[0].bulk
value := args[1].bulk
SETsMu.Lock()
SETs[key] = value
SETsMu.Unlock()
return Value{typ: "string", str: "OK"}
}
func get(args []Value) Value {
if len(args) != 1 {
return Value{typ: "error", str: "ERROR wrong number of arguments for 'get' command"}
}
key := args[0].bulk
SETsMu.RLock()
value, ok := SETs[key]
SETsMu.RUnlock()
if !ok {
return Value{typ: "null"}
}
return Value{typ: "bulk", bulk: value}
}
var HSETs = map[string]map[string]string{}
var HSETsMu = sync.RWMutex{}
func hset(args []Value) Value {
if len(args) != 3 {
return Value{typ: "error", str: "ERR wrong number of arguments for 'hset' command"}
}
hash := args[0].bulk
key := args[1].bulk
value := args[2].bulk
HSETsMu.Lock()
if _, ok := HSETs[hash]; !ok {
HSETs[hash] = map[string]string{}
}
HSETs[hash][key] = value
HSETsMu.Unlock()
return Value{typ: "string", str: "OK"}
}
func hget(args []Value) Value {
if len(args) != 2 {
return Value{typ: "error", str: "ERR wrong number of arguments for 'hget' command"}
}
hash := args[0].bulk
key := args[1].bulk
HSETsMu.RLock()
value, ok := HSETs[hash][key]
HSETsMu.RUnlock()
if !ok {
return Value{typ: "null"}
}
return Value{typ: "bulk", bulk: value}
}
func hgetall(args []Value) Value {
if len(args) != 1 {
return Value{typ: "error", str: "Err "}
}
hash := args[0].bulk
HSETsMu.RLock()
value, ok := HSETs[hash]
if !ok {
return Value{typ: "null"}
}
values := []Value{}
for k, v := range value {
values = append(values, Value{typ: "bulk", bulk: k})
values = append(values, Value{typ: "bulk", bulk: v})
}
return Value{typ: "array", array: values}
}