forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_utils.go
78 lines (65 loc) · 2.08 KB
/
http_utils.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
package tests
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// Creates a new HTTP client with KeepAlive disabled.
func NewHTTPClient() *http.Client {
return &http.Client{Transport: &http.Transport{DisableKeepAlives: true}}
}
// Reads the body from the response and closes it.
func ReadBody(resp *http.Response) []byte {
if resp == nil {
return []byte{}
}
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
return body
}
// Reads the body from the response and parses it as JSON.
func ReadBodyJSON(resp *http.Response) map[string]interface{} {
m := make(map[string]interface{})
b := ReadBody(resp)
if err := json.Unmarshal(b, &m); err != nil {
panic(fmt.Sprintf("HTTP body JSON parse error: %v: %s", err, string(b)))
}
return m
}
func Head(url string) (*http.Response, error) {
return send("HEAD", url, "application/json", nil)
}
func Get(url string) (*http.Response, error) {
return send("GET", url, "application/json", nil)
}
func Post(url string, bodyType string, body io.Reader) (*http.Response, error) {
return send("POST", url, bodyType, body)
}
func PostForm(url string, data url.Values) (*http.Response, error) {
return Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}
func Put(url string, bodyType string, body io.Reader) (*http.Response, error) {
return send("PUT", url, bodyType, body)
}
func PutForm(url string, data url.Values) (*http.Response, error) {
return Put(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}
func Delete(url string, bodyType string, body io.Reader) (*http.Response, error) {
return send("DELETE", url, bodyType, body)
}
func DeleteForm(url string, data url.Values) (*http.Response, error) {
return Delete(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}
func send(method string, url string, bodyType string, body io.Reader) (*http.Response, error) {
c := NewHTTPClient()
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", bodyType)
return c.Do(req)
}