Home  >  Article  >  Backend Development  >  How do I bind an `http.Client` to a specific IP address in Go?

How do I bind an `http.Client` to a specific IP address in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 01:48:29893browse

How do I bind an `http.Client` to a specific IP address in Go?

Binding an http.Client to a Specific IP Address in Go

When dealing with multiple network interfaces on a client machine, it becomes imperative to bind an http.Client to a specific NIC or SRC IP address to ensure precise network traffic routing. The following guide will walk you through the necessary steps to achieve this in Go.

To begin, it's crucial to set the http.Client.Transport field to an instance of net.Transport. This allows you to specify the net.Dialer you intend to use. Subsequently, net.Dialer empowers you to define the local address from which connections are initiated.

Consider the following code snippet:

<code class="go">localAddr, err := net.ResolveIPAddr("ip", "<my local address>")
if err != nil {
  panic(err)
}

localTCPAddr := net.TCPAddr{
    IP: localAddr.IP,
}

webclient := &http.Client{
    Transport: &http.Transport{
        Proxy: http.ProxyFromEnvironment,
        DialContext: (&net.Dialer{
            LocalAddr: &localTCPAddr,
            Timeout:   30 * time.Second,
            KeepAlive: 30 * time.Second,
            DualStack: true,
        }).DialContext,
        MaxIdleConns:          100,
        IdleConnTimeout:       90 * time.Second,
        TLSHandshakeTimeout:   10 * time.Second,
        ExpectContinueTimeout: 1 * time.Second,
    },
}</code>

By following these steps, you can effectively bind your http.Client to a specific IP address, ensuring control over the network traffic originating from your client machine.

The above is the detailed content of How do I bind an `http.Client` to a specific IP address in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn