summaryrefslogtreecommitdiff
path: root/cautious_http_client.go
diff options
context:
space:
mode:
Diffstat (limited to 'cautious_http_client.go')
-rw-r--r--cautious_http_client.go80
1 files changed, 80 insertions, 0 deletions
diff --git a/cautious_http_client.go b/cautious_http_client.go
new file mode 100644
index 0000000..66179f2
--- /dev/null
+++ b/cautious_http_client.go
@@ -0,0 +1,80 @@
1package main
2
3import (
4 "encoding/json"
5 "net"
6 "net/http"
7 "net/url"
8 "time"
9)
10
11type CautiousHTTPClient interface {
12 Get(string) (*http.Response, error)
13 GetJSON(string, interface{}) error
14}
15
16type cautiousHttpClient struct {
17 client *http.Client
18}
19
20func NewCautiousHTTPClient() CautiousHTTPClient {
21 // May Need: TLSClientConfig *tls.Config
22 CautiousTransport := &http.Transport{
23 Proxy: http.ProxyFromEnvironment,
24 DialContext: (&net.Dialer{
25 Timeout: 1 * time.Second,
26 KeepAlive: 30 * time.Second,
27 DualStack: true,
28 }).DialContext,
29 MaxIdleConns: 100,
30 IdleConnTimeout: 90 * time.Second,
31 TLSHandshakeTimeout: 3 * time.Second,
32 ExpectContinueTimeout: 1 * time.Second,
33 ResponseHeaderTimeout: 5 * time.Second,
34 MaxResponseHeaderBytes: 500000, // .5 MB
35 }
36
37 return &cautiousHttpClient{
38 client: &http.Client{
39 Transport: CautiousTransport,
40 Timeout: 30 * time.Second,
41 },
42 }
43}
44
45func (c *cautiousHttpClient) Get(gurl string) (*http.Response, error) {
46 u, err := url.Parse(gurl)
47 if err != nil {
48 return nil, err
49 }
50
51 // TODO
52 /*
53 if u.Scheme != "https" {
54 return nil, fmt.Errorf("URL for GET must be secure")
55 }
56 */
57
58 r, err := c.client.Get(u.String())
59 if err != nil {
60 return nil, err
61 }
62 r.Body = http.MaxBytesReader(nil, r.Body, 1000000)
63 return r, err
64}
65
66func (c *cautiousHttpClient) GetJSON(url string, rv interface{}) error {
67 r, err := c.Get(url)
68 if err != nil {
69 return err
70 }
71 defer r.Body.Close()
72
73 d := json.NewDecoder(r.Body)
74 err = d.Decode(rv)
75 if err != nil {
76 return err
77 }
78
79 return nil
80}