-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
99 lines (79 loc) · 1.39 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"bytes"
"errors"
"net/url"
)
type Command struct {
wr bool
value []byte
}
var CmdError = errors.New("read: requested unknown action")
func NewCommand(buf []byte) (cmd *Command, err error) {
var (
conv_str string
)
cmd = &Command{
value: bytes.ToLower(buf),
}
if conv_str, err = url.QueryUnescape(string(cmd.value)); err != nil {
return nil, err
} else {
cmd.value = []byte(conv_str)
}
if err = cmd.init(); err != nil {
return nil, err
}
cmd.clear()
return
}
func (this *Command) GetStr() string {
return string(this.value)
}
func (this *Command) init() error {
var (
prefix = [][]byte{
[]byte("get "),
[]byte("put "),
}
)
for idx, val := range prefix {
if bytes.HasPrefix(this.value, val) {
this.value = bytes.TrimPrefix(this.value, val)
switch idx {
case 1:
this.wr = true
default:
this.wr = false
}
return nil
}
}
return CmdError
}
func (this *Command) clear() {
for {
if b, ok := hasGarbage(this.value); ok {
this.value = bytes.TrimPrefix(this.value, b)
this.value = bytes.TrimSuffix(this.value, b)
continue
}
break
}
}
func hasGarbage(b []byte) ([]byte, bool) {
var (
garbage = []byte{
0x00,
0x0a,
0x0d,
0x20,
}
)
for _, g := range garbage {
if bytes.HasPrefix(b, []byte{g}) || bytes.HasSuffix(b, []byte{g}) {
return []byte{g}, true
}
}
return nil, false
}