Home > Backend Development > Golang > How Can I Bind a Go HTTP Client to a Specific IP Address?

How Can I Bind a Go HTTP Client to a Specific IP Address?

Patricia Arquette
Release: 2024-10-29 12:24:29
Original
929 people have browsed it

How Can I Bind a Go HTTP Client to a Specific IP Address?

Binding an http.Client to an IP Address in Go

In the realm of distributed computing, it's often necessary to control the source IP address from which HTTP requests originate. With multiple NICs on a client machine, this granularity can be essential.

Consider the following basic HTTP client code:

<code class="go">package main

import "net/http"

func main() {
    webclient := &http.Client{}
    req, _ := http.NewRequest("GET", "http://www.google.com", nil)
    httpResponse, _ := webclient.Do(req)
    defer httpResponse.Body.Close()
}</code>
Copy after login

To bind this client to a specific NIC or IP address, we need to modify its Transport field. We'll use a custom net.Transport that employs a custom net.Dialer. The net.Dialer, in turn, allows us to specify the local address for outgoing connections.

<code class="go">import (
    "net"
    "net/http"
)

func main() {
    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}).DialContext,
            MaxIdleConns:          100,
            IdleConnTimeout:       90 * time.Second,
            TLSHandshakeTimeout:   10 * time.Second,
            ExpectContinueTimeout: 1 * time.Second,
        },
    }
}</code>
Copy after login

With this modification, our HTTP client is now bound to the specified IP address, ensuring that all outgoing requests originate from the desired NIC.

The above is the detailed content of How Can I Bind a Go HTTP Client to a Specific IP Address?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template