summaryrefslogtreecommitdiff
path: root/cautious_http_client.go
blob: 34b736fc3e0bb25d74795e7c04064f96ec8fcfe5 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main

import (
	"encoding/json"
	"github.com/lox/httpcache"
	"github.com/pkg/errors"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"
)

type CautiousHTTPClient interface {
	Get(string) (*http.Response, error)
	GetJSON(string, interface{}) error
	GetJSONExpires(string, interface{}) (time.Duration, error)
}

type cautiousHttpClient struct {
	allowHttp bool
	client    *http.Client
}

// allowHttp is UNSAFE and technically validates the spec but it does make it
// easier to work in dev so leaving it in for now
func NewCautiousHTTPClient(allowHttp bool) (CautiousHTTPClient, error) {
	CautiousTransport := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   1 * time.Second,
			KeepAlive: 30 * time.Second,
			DualStack: true,
		}).DialContext,
		MaxIdleConns:           100,
		IdleConnTimeout:        90 * time.Second,
		TLSHandshakeTimeout:    1 * time.Second,
		ExpectContinueTimeout:  1 * time.Second,
		ResponseHeaderTimeout:  10 * time.Second,
		MaxResponseHeaderBytes: 500000, // .5 MB
	}

	return &cautiousHttpClient{
		allowHttp: allowHttp,
		client: &http.Client{
			Transport: CautiousTransport,
			Timeout:   30 * time.Second,
		},
	}, nil
}

func (c *cautiousHttpClient) Get(gurl string) (*http.Response, error) {
	u, err := url.Parse(gurl)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	if u.Scheme != "https" && !c.allowHttp {
		return nil, errors.Errorf("URL for GET must be secure")
	}

	r, err := c.client.Get(u.String())
	if err != nil {
		return nil, errors.WithStack(err)
	}
	r.Body = http.MaxBytesReader(nil, r.Body, 1000000)

	return r, nil
}

func (c *cautiousHttpClient) GetJSON(url string, rv interface{}) error {
	r, err := c.Get(url)
	if err != nil {
		return errors.WithStack(err)
	}
	defer r.Body.Close()

	d := json.NewDecoder(r.Body)
	err = d.Decode(rv)
	if err != nil {
		return errors.WithStack(err)
	}

	return nil
}

func (c *cautiousHttpClient) GetJSONExpires(url string, rv interface{}) (time.Duration, error) {
	r, err := c.Get(url)
	if err != nil {
		return time.Duration(0), errors.WithStack(err)
	}
	defer r.Body.Close()

	res := httpcache.NewResource(r.StatusCode, nil, r.Header)

	d := json.NewDecoder(r.Body)
	err = d.Decode(rv)
	if err != nil {
		return time.Duration(0), errors.WithStack(err)
	}

	return refreshAfter(res), nil
}

type JSONURL struct {
	*url.URL
}

func (u *JSONURL) AsURL() *url.URL {
	return u.URL
}

func (u *JSONURL) UnmarshalJSON(data []byte) error {
	d := strings.Trim(string(data), "\"")
	pu, err := url.Parse(d)
	if err != nil {
		return errors.WithStack(err)
	}

	u.URL = pu
	return nil
}

func refreshAfter(res *httpcache.Resource) time.Duration {
	maxAge, err := res.MaxAge(false)
	if err != nil {
		return time.Duration(0)
	}

	age, err := res.Age()
	if err != nil {
		return time.Duration(0)
	}

	if hFresh := res.HeuristicFreshness(); hFresh > maxAge {
		maxAge = hFresh
	}

	return maxAge - age
}