fix: fall back to ipv4 when ipv6 is unreachable
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
package netutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -16,10 +19,28 @@ func newTransport(dialTimeout, tlsTimeout, headerTimeout time.Duration) *http.Tr
|
||||
TLSHandshakeTimeout: tlsTimeout,
|
||||
ResponseHeaderTimeout: headerTimeout,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DialContext: dialer.DialContext,
|
||||
DialContext: dialWithIPv4Fallback(dialer),
|
||||
}
|
||||
}
|
||||
|
||||
func dialWithIPv4Fallback(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
|
||||
return func(ctx context.Context, network string, address string) (net.Conn, error) {
|
||||
conn, err := dialer.DialContext(ctx, network, address)
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
if network != "tcp" || !isUnreachableNetwork(err) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dialer.DialContext(ctx, "tcp4", address)
|
||||
}
|
||||
}
|
||||
|
||||
func isUnreachableNetwork(err error) bool {
|
||||
return errors.Is(err, syscall.ENETUNREACH) || errors.Is(err, syscall.EHOSTUNREACH)
|
||||
}
|
||||
|
||||
func NewClient() *http.Client {
|
||||
return &http.Client{
|
||||
Transport: newTransport(10*time.Second, 10*time.Second, 30*time.Second),
|
||||
|
||||
Reference in New Issue
Block a user