generic_http.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Generic HTTP transport for imgproxy
  2. package generichttp
  3. import (
  4. "crypto/tls"
  5. "net"
  6. "net/http"
  7. "syscall"
  8. "time"
  9. "github.com/imgproxy/imgproxy/v3/security"
  10. "golang.org/x/net/http2"
  11. )
  12. func New(verifyNetworks bool, config *Config) (*http.Transport, error) {
  13. if err := config.Validate(); err != nil {
  14. return nil, err
  15. }
  16. dialer := &net.Dialer{
  17. Timeout: 30 * time.Second,
  18. KeepAlive: 30 * time.Second,
  19. DualStack: true,
  20. }
  21. if verifyNetworks {
  22. dialer.Control = func(network, address string, c syscall.RawConn) error {
  23. return security.VerifySourceNetwork(address)
  24. }
  25. }
  26. transport := &http.Transport{
  27. Proxy: http.ProxyFromEnvironment,
  28. DialContext: dialer.DialContext,
  29. MaxIdleConns: 100,
  30. MaxIdleConnsPerHost: 100,
  31. IdleConnTimeout: time.Duration(config.ClientKeepAliveTimeout) * time.Second,
  32. TLSHandshakeTimeout: 10 * time.Second,
  33. ExpectContinueTimeout: 1 * time.Second,
  34. ForceAttemptHTTP2: false,
  35. DisableCompression: true,
  36. HTTP2: &http.HTTP2Config{
  37. MaxReceiveBufferPerStream: 128 * 1024,
  38. },
  39. }
  40. if config.ClientKeepAliveTimeout <= 0 {
  41. transport.MaxIdleConnsPerHost = -1
  42. transport.DisableKeepAlives = true
  43. }
  44. if config.IgnoreSslVerification {
  45. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  46. }
  47. transport2, err := http2.ConfigureTransports(transport)
  48. if err != nil {
  49. return nil, err
  50. }
  51. // TODO: Move this to transport.HTTP2 when https://go.dev/issue/67813 is closed
  52. transport2.MaxReadFrameSize = 16 * 1024
  53. transport2.PingTimeout = 5 * time.Second
  54. transport2.ReadIdleTimeout = time.Second
  55. return transport, nil
  56. }