github.com/ghodss/etcd@v0.3.1-0.20140417172404-cc329bfa55cb/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: %s", err, string(b)))
    34  	}
    35  	return m
    36  }
    37  
    38  func Head(url string) (*http.Response, error) {
    39  	return send("HEAD", url, "application/json", nil)
    40  }
    41  
    42  func Get(url string) (*http.Response, error) {
    43  	return send("GET", url, "application/json", nil)
    44  }
    45  
    46  func Post(url string, bodyType string, body io.Reader) (*http.Response, error) {
    47  	return send("POST", url, bodyType, body)
    48  }
    49  
    50  func PostForm(url string, data url.Values) (*http.Response, error) {
    51  	return Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
    52  }
    53  
    54  func Put(url string, bodyType string, body io.Reader) (*http.Response, error) {
    55  	return send("PUT", url, bodyType, body)
    56  }
    57  
    58  func PutForm(url string, data url.Values) (*http.Response, error) {
    59  	return Put(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
    60  }
    61  
    62  func Delete(url string, bodyType string, body io.Reader) (*http.Response, error) {
    63  	return send("DELETE", url, bodyType, body)
    64  }
    65  
    66  func DeleteForm(url string, data url.Values) (*http.Response, error) {
    67  	return Delete(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
    68  }
    69  
    70  func send(method string, url string, bodyType string, body io.Reader) (*http.Response, error) {
    71  	c := NewHTTPClient()
    72  	req, err := http.NewRequest(method, url, body)
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  	req.Header.Set("Content-Type", bodyType)
    77  	return c.Do(req)
    78  }