/
http.go
65 lines (53 loc) · 1.4 KB
/
http.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
package utils
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"os"
"github.com/pkg/errors"
)
func DownloadUrl(url string, path string) error {
// create output file
output, err := os.Create(path)
if err != nil {
return errors.Wrap(err, "Create output file")
}
defer output.Close()
// do http call
response, err := http.Get(url)
if err != nil {
return errors.Wrap(err, "Http error")
}
defer response.Body.Close()
if response.StatusCode >= http.StatusBadRequest {
b, _ := ioutil.ReadAll(response.Body)
return errors.Errorf("Http Error: %s", string(b))
}
// download to output file
_, err = io.Copy(output, response.Body)
if err != nil {
return errors.Wrap(err, "Download error")
}
return nil
}
// Send http POST request.
// Note that json encoding errors are ignored. We expect a valid payload
// based on https://www.zupzup.org/io-pipe-go/
func HttpPostJson(url string, payload interface{}) (*http.Response, error) {
pr, pw := io.Pipe()
go func() {
// close the writer, so the reader knows there's no more data
defer pw.Close()
// write json data to the PipeReader through the PipeWriter
json.NewEncoder(pw).Encode(&payload)
}()
// JSON from the PipeWriter lands in the PipeReader
// ...and we send it off...
var resp *http.Response
resp, err := http.Post(url, "application/json", pr)
if err != nil {
return nil, errors.Wrap(err, "http.Post")
}
return resp, nil
}