github.com/qiniu/go-sdk/v7@v7.27.0/client/dialer.go (about) 1 package client 2 3 import ( 4 "context" 5 "net" 6 "time" 7 8 "github.com/qiniu/go-sdk/v7/internal/dialer" 9 ) 10 11 type ( 12 resolverContextKey struct{} 13 dialTimeoutContextKey struct{} 14 keepAliveIntervalContextKey struct{} 15 resolverContextValue struct { 16 domain string 17 ips []net.IP 18 } 19 ) 20 21 func defaultDialFunc(ctx context.Context, network string, address string) (net.Conn, error) { 22 host, port, err := net.SplitHostPort(address) 23 if err != nil { 24 host = address 25 } 26 27 dialTimeout, ok := ctx.Value(dialTimeoutContextKey{}).(time.Duration) 28 if !ok { 29 dialTimeout = 30 * time.Second 30 } 31 keepAliveInterval, ok := ctx.Value(keepAliveIntervalContextKey{}).(time.Duration) 32 if !ok { 33 keepAliveInterval = 15 * time.Second 34 } 35 if resolved, ok := ctx.Value(resolverContextKey{}).(resolverContextValue); ok && len(resolved.ips) > 0 && resolved.domain == host { 36 return dialer.DialContext(ctx, network, resolved.ips, port, dialer.DialOptions{Timeout: dialTimeout, KeepAlive: keepAliveInterval}) 37 } 38 return (&net.Dialer{Timeout: dialTimeout, KeepAlive: keepAliveInterval}).DialContext(ctx, network, address) 39 } 40 41 func WithResolvedIPs(ctx context.Context, domain string, ips []net.IP) context.Context { 42 return context.WithValue(ctx, resolverContextKey{}, resolverContextValue{domain: domain, ips: ips}) 43 } 44 45 func WithDialTimeout(ctx context.Context, timeout time.Duration) context.Context { 46 return context.WithValue(ctx, dialTimeoutContextKey{}, timeout) 47 } 48 49 func WithKeepAliveInterval(ctx context.Context, interval time.Duration) context.Context { 50 return context.WithValue(ctx, keepAliveIntervalContextKey{}, interval) 51 }