"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-10
Browse:525

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:

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()
}

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.

import (
    "net"
    "net/http"
)

func main() {
    localAddr, err := net.ResolveIPAddr("ip", "")
    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,
        },
    }
}

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3