Issue:
Using Go 1.11's net/http client, how can one determine if a domain is IPv6-only and prevent it from using IPv4 if desired?
Solution:
To enforce IPv4 or IPv6 usage in Go's net/http client, modify its DialContext function using the Control option of the net.Dialer. This function checks the network type used for outgoing connections.
Copy the following code into your main function:
<code class="go">func ModifiedTransport() { var MyTransport = &http.Transport{ DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: false, Control: func(network, address string, c syscall.RawConn) error { if network == "ipv4" { // Force cancellation of IPv4 connections return errors.New("you should not use ipv4") } return nil }, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } var myClient = http.Client{Transport: MyTransport} resp, myerr := myClient.Get("http://www.github.com") if myerr != nil { fmt.Println("request error") return } var buffer = make([]byte, 1000) resp.Body.Read(buffer) fmt.Println(string(buffer)) }</code>
Explanation:
The above is the detailed content of How to Enforce IPv4/IPv6 Usage in Go\'s net/http Client?. For more information, please follow other related articles on the PHP Chinese website!