1package simplehttp 2 3import ( 4 "bytes" 5 "io" 6 "io/ioutil" 7 "net/http" 8 "net/url" 9 "strings" 10) 11 12// Behaves as https://golang.org/pkg/net/http/#Client.Do with the exception that 13// the Response.Body does not need to be closed. This function should generally 14// only be used when it is already known that the response body will be 15// relatively small, as it will be completely read into memory. 16func Do(client *http.Client, req *http.Request) (*http.Response, error) { 17 if client == nil { 18 client = http.DefaultClient 19 } 20 resp, err := client.Do(req) 21 if err != nil { 22 return nil, err 23 } 24 defer resp.Body.Close() 25 26 bb := &bytes.Buffer{} 27 n, err := io.Copy(bb, resp.Body) 28 if err != nil { 29 return nil, err 30 } 31 32 resp.ContentLength = n 33 resp.Body = ioutil.NopCloser(bb) 34 35 return resp, nil 36} 37 38// Behaves as https://golang.org/pkg/net/http/#Get but uses simplehttp.Do() to 39// make the request. 40func Get(url string) (*http.Response, error) { 41 req, err := http.NewRequest("GET", url, nil) 42 if err != nil { 43 return nil, err 44 } 45 return Do(http.DefaultClient, req) 46} 47 48// Behaves as https://golang.org/pkg/net/http/#Head but uses simplehttp.Do() to 49// make the request. 50func Head(url string) (*http.Response, error) { 51 req, err := http.NewRequest("HEAD", url, nil) 52 if err != nil { 53 return nil, err 54 } 55 return Do(http.DefaultClient, req) 56} 57 58// Behaves as https://golang.org/pkg/net/http/#Post but uses simplehttp.Do() to 59// make the request. 60func Post(url string, bodyType string, body io.Reader) (*http.Response, error) { 61 req, err := http.NewRequest("POST", url, nil) 62 if err != nil { 63 return nil, err 64 } 65 req.Header.Set("Content-Type", bodyType) 66 return Do(http.DefaultClient, req) 67} 68 69// Behaves as https://golang.org/pkg/net/http/#PostForm but uses simplehttp.Do() 70// to make the request. 71func PostForm(url string, data url.Values) (*http.Response, error) { 72 return Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) 73} 74