github.com/macb/etcd@v0.3.1-0.20140227003422-a60481c6b1a0/tests/http_utils.go (about) 1 package tests 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "io/ioutil" 8 "net/http" 9 "net/url" 10 "strings" 11 ) 12 13 // Creates a new HTTP client with KeepAlive disabled. 14 func NewHTTPClient() *http.Client { 15 return &http.Client{Transport: &http.Transport{DisableKeepAlives: true}} 16 } 17 18 // Reads the body from the response and closes it. 19 func ReadBody(resp *http.Response) []byte { 20 if resp == nil { 21 return []byte{} 22 } 23 body, _ := ioutil.ReadAll(resp.Body) 24 resp.Body.Close() 25 return body 26 } 27 28 // Reads the body from the response and parses it as JSON. 29 func ReadBodyJSON(resp *http.Response) map[string]interface{} { 30 m := make(map[string]interface{}) 31 b := ReadBody(resp) 32 if err := json.Unmarshal(b, &m); err != nil { 33 panic(fmt.Sprintf("HTTP body JSON parse error: %v", err)) 34 } 35 return m 36 } 37 38 func Get(url string) (*http.Response, error) { 39 return send("GET", url, "application/json", nil) 40 } 41 42 func Post(url string, bodyType string, body io.Reader) (*http.Response, error) { 43 return send("POST", url, bodyType, body) 44 } 45 46 func PostForm(url string, data url.Values) (*http.Response, error) { 47 return Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) 48 } 49 50 func Put(url string, bodyType string, body io.Reader) (*http.Response, error) { 51 return send("PUT", url, bodyType, body) 52 } 53 54 func PutForm(url string, data url.Values) (*http.Response, error) { 55 return Put(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) 56 } 57 58 func Delete(url string, bodyType string, body io.Reader) (*http.Response, error) { 59 return send("DELETE", url, bodyType, body) 60 } 61 62 func DeleteForm(url string, data url.Values) (*http.Response, error) { 63 return Delete(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) 64 } 65 66 func send(method string, url string, bodyType string, body io.Reader) (*http.Response, error) { 67 c := NewHTTPClient() 68 req, err := http.NewRequest(method, url, body) 69 if err != nil { 70 return nil, err 71 } 72 req.Header.Set("Content-Type", bodyType) 73 return c.Do(req) 74 }