-
Notifications
You must be signed in to change notification settings - Fork 3
/
http_request.go
85 lines (67 loc) · 1.58 KB
/
http_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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)
const (
userAgentHeader = "User-Agent"
defaultUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; +https://github.com/thekvs/yandex-ddns)"
)
const defaultNetworkTimeout = 20 * time.Second
var client = &http.Client{Timeout: defaultNetworkTimeout}
func postURL(url string, token *string, values *url.Values) ([]byte, error) {
var (
req *http.Request
err error
)
if values != nil {
req, err = http.NewRequest("POST", url, bytes.NewBufferString(values.Encode()))
} else {
req, err = http.NewRequest("POST", url, nil)
}
if err != nil {
log.Fatalf("%s", err)
}
if token != nil && len(*token) > 0 {
req.Header.Add("pddToken", *token)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
resp, err := client.Do(req)
if err != nil {
log.Fatalf("%s", err)
}
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
log.Fatalf("%s", err)
}
return body, nil
}
func getURL(url string, token *string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Add(userAgentHeader, defaultUserAgent)
if token != nil && len(*token) > 0 {
req.Header.Add("pddToken", *token)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer closeResource(resp.Body)
if resp.StatusCode != 200 {
return nil, fmt.Errorf("unexpecetd HTTP status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}