fix: fall back to ipv4 when ipv6 is unreachable

This commit is contained in:
2026-06-16 20:02:39 +02:00
committed by Milas Holsting
parent 99d5d89fe1
commit ff1ce6588a
2 changed files with 23 additions and 2 deletions

View File

@@ -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),