http.go 748 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package mastodon
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "time"
  7. )
  8. type lr struct {
  9. io.ReadCloser
  10. n int64
  11. r *http.Request
  12. }
  13. func (r *lr) Read(p []byte) (n int, err error) {
  14. if r.n <= 0 {
  15. return 0, fmt.Errorf("%s \"%s\": response body too large", r.r.Method, r.r.URL)
  16. }
  17. if int64(len(p)) > r.n {
  18. p = p[0:r.n]
  19. }
  20. n, err = r.ReadCloser.Read(p)
  21. r.n -= int64(n)
  22. return
  23. }
  24. type transport struct {
  25. t http.RoundTripper
  26. }
  27. func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) {
  28. resp, err := t.t.RoundTrip(r)
  29. if resp != nil && resp.Body != nil {
  30. resp.Body = &lr{resp.Body, 8 << 20, r}
  31. }
  32. return resp, err
  33. }
  34. var httpClient = &http.Client{
  35. Transport: &transport{
  36. t: http.DefaultTransport,
  37. },
  38. Timeout: 30 * time.Second,
  39. }