forked from hoisie/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
369 lines (331 loc) · 10.2 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package web
import (
"fmt"
"http"
"io"
"io/ioutil"
"json"
"mime"
"mime/multipart"
"net"
"os"
"reflect"
"strconv"
"strings"
"url"
)
type filedata struct {
Filename string
Data []byte
}
type Request struct {
Method string // GET, POST, PUT, etc.
RawURL string // The raw URL given in the request.
URL *url.URL // Parsed URL.
Proto string // "HTTP/1.0"
ProtoMajor int // 1
ProtoMinor int // 0
Headers http.Header
Body io.Reader
Close bool
Host string
Referer string
UserAgent string
FullParams map[string][]string
Params map[string]string
ParamData []byte
Cookies map[string]string
Cookie []*http.Cookie
Files map[string]filedata
RemoteAddr string
RemotePort int
}
type badStringError struct {
what string
str string
}
func (e *badStringError) String() string { return fmt.Sprintf("%s %q", e.what, e.str) }
func flattenParams(fullParams map[string][]string) map[string]string {
params := map[string]string{}
for name, lst := range fullParams {
if len(lst) > 0 {
params[name] = lst[0]
}
}
return params
}
func newRequest(hr *http.Request, hc http.ResponseWriter) *Request {
remoteAddrIP, remotePort := hr.RemoteAddr, 0
remoteAddr, _ := net.ResolveTCPAddr("tcp", hr.RemoteAddr)
if remoteAddr != nil {
remoteAddrIP = remoteAddr.IP.String()
remotePort = remoteAddr.Port
}
req := Request{
Method: hr.Method,
URL: hr.URL,
Proto: hr.Proto,
ProtoMajor: hr.ProtoMajor,
ProtoMinor: hr.ProtoMinor,
Headers: hr.Header,
Body: hr.Body,
Close: hr.Close,
Host: hr.Host,
Referer: hr.Referer(),
UserAgent: hr.UserAgent(),
FullParams: hr.Form,
Cookie: hr.Cookies(),
RemoteAddr: remoteAddrIP,
RemotePort: remotePort,
}
return &req
}
func newRequestCgi(headers http.Header, body io.Reader) *Request {
var httpheader = make(http.Header)
for header, value := range headers {
if strings.HasPrefix(header, "Http_") {
newHeader := header[5:]
newHeader = strings.Replace(newHeader, "_", "-", -1)
newHeader = http.CanonicalHeaderKey(newHeader)
httpheader[newHeader] = value
}
}
host := httpheader.Get("Host")
method := headers.Get("REQUEST_METHOD")
path := headers.Get("REQUEST_URI")
port := headers.Get("SERVER_PORT")
proto := headers.Get("SERVER_PROTOCOL")
rawurl := "http://" + host + ":" + port + path
url_, _ := url.Parse(rawurl)
useragent := headers.Get("USER_AGENT")
remoteAddr := headers.Get("REMOTE_ADDR")
remotePort, _ := strconv.Atoi(headers.Get("REMOTE_PORT"))
if method == "POST" {
if ctype, ok := headers["CONTENT_TYPE"]; ok {
httpheader["Content-Type"] = ctype
}
if clength, ok := headers["CONTENT_LENGTH"]; ok {
httpheader["Content-Length"] = clength
}
}
//read the cookies
cookies := readCookies(httpheader)
req := Request{
Method: method,
RawURL: rawurl,
URL: url_,
Proto: proto,
Host: host,
UserAgent: useragent,
Body: body,
Headers: httpheader,
RemoteAddr: remoteAddr,
RemotePort: remotePort,
Cookie: cookies,
}
return &req
}
func parseForm(m map[string][]string, query string) (err os.Error) {
for _, kv := range strings.Split(query, "&") {
kvPair := strings.SplitN(kv, "=", 2)
var key, value string
var e os.Error
key, e = url.QueryUnescape(kvPair[0])
if e == nil && len(kvPair) > 1 {
value, e = url.QueryUnescape(kvPair[1])
}
if e != nil {
err = e
}
vec, ok := m[key]
if !ok {
vec = []string{}
}
m[key] = append(vec, value)
}
return
}
// ParseForm parses the request body as a form for POST requests, or the raw query for GET requests.
// It is idempotent.
func (r *Request) parseParams() (err os.Error) {
if r.Params != nil {
return
}
r.FullParams = make(map[string][]string)
queryParams := r.URL.RawQuery
var bodyParams string
switch r.Method {
case "POST":
if r.Body == nil {
return os.NewError("missing form body")
}
ct := r.Headers.Get("Content-Type")
switch strings.SplitN(ct, ";", 2)[0] {
case "text/plain", "application/x-www-form-urlencoded", "":
var b []byte
if b, err = ioutil.ReadAll(r.Body); err != nil {
return err
}
bodyParams = string(b)
case "application/json":
//if we get JSON, do the best we can to convert it to a map[string]string
//we make the body available as r.ParamData
var b []byte
if b, err = ioutil.ReadAll(r.Body); err != nil {
return err
}
r.ParamData = b
r.Params = map[string]string{}
json.Unmarshal(b, r.Params)
case "multipart/form-data":
_, params := mime.ParseMediaType(ct)
boundary, ok := params["boundary"]
if !ok {
return os.NewError("Missing Boundary")
}
reader := multipart.NewReader(r.Body, boundary)
r.Files = make(map[string]filedata)
for {
part, err := reader.NextPart()
if part == nil && err == os.EOF {
break
}
if err != nil {
return err
}
//read the data
data, _ := ioutil.ReadAll(part)
//check for the 'filename' param
v := part.Header.Get("Content-Disposition")
if v == "" {
continue
}
name := part.FormName()
d, params := mime.ParseMediaType(v)
if d != "form-data" {
continue
}
if params["filename"] != "" {
r.Files[name] = filedata{params["filename"], data}
} else {
var params []string = r.FullParams[name]
params = append(params, string(data))
r.FullParams[name] = params
}
}
default:
return &badStringError{"unknown Content-Type", ct}
}
}
if queryParams != "" {
err = parseForm(r.FullParams, queryParams)
if err != nil {
return err
}
}
if bodyParams != "" {
err = parseForm(r.FullParams, bodyParams)
if err != nil {
return err
}
}
r.Params = flattenParams(r.FullParams)
return nil
}
func (r *Request) HasFile(name string) bool {
if r.Files == nil || len(r.Files) == 0 {
return false
}
_, ok := r.Files[name]
return ok
}
func writeTo(s string, val reflect.Value) os.Error {
switch v := val; v.Kind() {
// if we're writing to an interace value, just set the byte data
// TODO: should we support writing to a pointer?
case reflect.Interface:
v.Set(reflect.ValueOf(s))
case reflect.Bool:
if strings.ToLower(s) == "false" || s == "0" {
v.SetBool(false)
} else {
v.SetBool(true)
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.Atoi64(s)
if err != nil {
return err
}
v.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
ui, err := strconv.Atoui64(s)
if err != nil {
return err
}
v.SetUint(ui)
case reflect.Float32, reflect.Float64:
f, err := strconv.Atof64(s)
if err != nil {
return err
}
v.SetFloat(f)
case reflect.String:
v.SetString(s)
case reflect.Slice:
typ := v.Type()
if typ.Elem().Kind() == reflect.Uint || typ.Elem().Kind() == reflect.Uint8 || typ.Elem().Kind() == reflect.Uint16 || typ.Elem().Kind() == reflect.Uint32 || typ.Elem().Kind() == reflect.Uint64 || typ.Elem().Kind() == reflect.Uintptr {
v.Set(reflect.ValueOf([]byte(s)))
}
}
return nil
}
// matchName returns true if key should be written to a field named name.
func matchName(key, name string) bool {
return strings.ToLower(key) == strings.ToLower(name)
}
func (r *Request) writeToContainer(val reflect.Value) os.Error {
switch v := val; v.Kind() {
case reflect.Ptr:
return r.writeToContainer(reflect.Indirect(v))
case reflect.Interface:
return r.writeToContainer(v.Elem())
case reflect.Map:
if v.Type().Key().Kind() != reflect.String {
return os.NewError("Invalid map type")
}
elemtype := v.Type().Elem()
for pk, pv := range r.Params {
mk := reflect.ValueOf(pk)
mv := reflect.Zero(elemtype)
writeTo(pv, mv)
v.SetMapIndex(mk, mv)
}
case reflect.Struct:
for pk, pv := range r.Params {
//try case sensitive match
field := v.FieldByName(pk)
if field.IsValid() {
writeTo(pv, field)
}
//try case insensitive matching
field = v.FieldByNameFunc(func(s string) bool { return matchName(pk, s) })
if field.IsValid() {
writeTo(pv, field)
}
}
default:
return os.NewError("Invalid container type")
}
return nil
}
func (r *Request) UnmarshalParams(val interface{}) os.Error {
if strings.HasPrefix(r.Headers.Get("Content-Type"), "application/json") {
return json.Unmarshal(r.ParamData, val)
} else {
err := r.writeToContainer(reflect.ValueOf(val))
if err != nil {
return err
}
}
return nil
}