forked from thatguystone/swan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
47 lines (39 loc) · 895 Bytes
/
http.go
File metadata and controls
47 lines (39 loc) · 895 Bytes
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
package swan
import (
"fmt"
"io"
"net/http"
"time"
"golang.org/x/net/context"
)
const (
maxRespBytes = 15728640
)
var (
httpClient = &http.Client{
Timeout: time.Second * 10,
}
)
func httpGet(url string) (body io.ReadCloser, resp *http.Response, err error) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
err = fmt.Errorf("could not create new request: %s", err)
return
}
req.Header.Set("User-Agent", "swan/"+Version)
resp, err = httpClient.Do(req)
if err != nil {
err = fmt.Errorf("could not load URL: %s", err)
return
}
if resp.StatusCode != 200 {
resp.Body.Close()
resp.Body = nil
err = fmt.Errorf("could not load URL: status code %d", resp.StatusCode)
return
}
body = http.MaxBytesReader(nil, resp.Body, maxRespBytes)
return
}