-
Notifications
You must be signed in to change notification settings - Fork 58
/
request.go
59 lines (51 loc) · 1.14 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
// Copyright 2012 Jimmy Zelinskie. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package geddit
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"net/url"
)
type request struct {
url string
values *url.Values
cookie *http.Cookie
useragent string
}
func (r request) getResponse() (*bytes.Buffer, error) {
// Determine the HTTP action.
var action, finalurl string
if r.values == nil {
action = "GET"
finalurl = r.url
} else {
action = "POST"
finalurl = r.url + "?" + r.values.Encode()
}
// Create a request and add the proper headers.
req, err := http.NewRequest(action, finalurl, nil)
if err != nil {
return nil, err
}
if r.cookie != nil {
req.AddCookie(r.cookie)
}
req.Header.Set("User-Agent", r.useragent)
// Handle the request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
respbytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bytes.NewBuffer(respbytes), nil
}