This repository has been archived by the owner on Mar 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 125
/
request.go
84 lines (75 loc) · 1.67 KB
/
request.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
package redis
import (
"io"
"strconv"
)
type Request struct {
Name string
Args [][]byte
Host string
ClientChan chan struct{}
Body io.ReadCloser
}
func (r *Request) HasArgument(index int) bool {
return len(r.Args) >= index+1
}
func (r *Request) ExpectArgument(index int) ReplyWriter {
if !r.HasArgument(index) {
return ErrNotEnoughArgs
}
return nil
}
func (r *Request) GetString(index int) (string, ReplyWriter) {
if reply := r.ExpectArgument(index); reply != nil {
return "", reply
}
return string(r.Args[index]), nil
}
func (r *Request) GetInteger(index int) (int, ReplyWriter) {
if reply := r.ExpectArgument(index); reply != nil {
return -1, reply
}
i, err := strconv.Atoi(string(r.Args[index]))
if err != nil {
return -1, ErrExpectInteger
}
return i, nil
}
func (r *Request) GetPositiveInteger(index int) (int, ReplyWriter) {
i, reply := r.GetInteger(index)
if reply != nil {
return -1, reply
}
if i < 0 {
return -1, ErrExpectPositivInteger
}
return i, nil
}
func (r *Request) GetStringSlice(index int) ([]string, ReplyWriter) {
if reply := r.ExpectArgument(index); reply != nil {
return nil, reply
}
var ret []string
for _, elem := range r.Args[index:] {
ret = append(ret, string(elem))
}
return ret, nil
}
func (r *Request) GetMap(index int) (map[string][]byte, ReplyWriter) {
count := len(r.Args) - index
if count <= 0 {
return nil, ErrExpectMorePair
}
if count%2 != 0 {
return nil, ErrExpectEvenPair
}
values := make(map[string][]byte)
for i := index; i < len(r.Args); i += 2 {
key, reply := r.GetString(i)
if reply != nil {
return nil, reply
}
values[key] = r.Args[i+1]
}
return values, nil
}