diff options
author | r <r@freesoftwareextremist.com> | 2023-09-17 09:44:02 +0000 |
---|---|---|
committer | r <r@freesoftwareextremist.com> | 2023-09-18 04:05:20 +0000 |
commit | ad38855261dca802439922f71408e2b08e7c10ea (patch) | |
tree | f87bb943c2285ea3ae32ecd3b0d2495ea97af5b8 /mastodon/http.go | |
parent | 60ccc9686a39ff67d3cf361c4e6848d79877b18b (diff) | |
download | bloat-ad38855261dca802439922f71408e2b08e7c10ea.tar.gz bloat-ad38855261dca802439922f71408e2b08e7c10ea.zip |
Set timeout and response size limit for the http client
Diffstat (limited to 'mastodon/http.go')
-rw-r--r-- | mastodon/http.go | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/mastodon/http.go b/mastodon/http.go new file mode 100644 index 0000000..ca4c771 --- /dev/null +++ b/mastodon/http.go @@ -0,0 +1,41 @@ +package mastodon + +import ( + "fmt" + "io" + "net/http" + "time" +) + +type lr struct { + io.ReadCloser + r *http.Request +} + +func (r *lr) Read(p []byte) (n int, err error) { + n, err = r.ReadCloser.Read(p) + // override the generic error returned by the MaxBytesReader + if _, ok := err.(*http.MaxBytesError); ok { + err = fmt.Errorf("%s \"%s\": response body too large", r.r.Method, r.r.URL) + } + return +} + +type transport struct { + t http.RoundTripper +} + +func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) { + resp, err := t.t.RoundTrip(r) + if resp != nil && resp.Body != nil { + resp.Body = &lr{http.MaxBytesReader(nil, resp.Body, 8<<20), r} + } + return resp, err +} + +var httpClient = &http.Client{ + Transport: &transport{ + t: http.DefaultTransport, + }, + Timeout: 30 * time.Second, +} |