Home > Backend Development > Golang > How to Customize the Source IP Address for HTTP Requests in Go?

How to Customize the Source IP Address for HTTP Requests in Go?

Mary-Kate Olsen
Release: 2024-12-26 05:33:53
Original
543 people have browsed it

How to Customize the Source IP Address for HTTP Requests in Go?

Customizing IP Source for HTTP Requests

In situations where you prefer to avoid using your primary IP address for HTTP requests, Go provides a way to specify the source address.

To achieve this, you can create a custom Dialer within the client's Transport. This is accomplished as follows:

// Create a transport based on http.DefaultTransport, but with a custom localAddr
transport := &http.Transport{
    Proxy: http.ProxyFromEnvironment,
    DialContext: (&net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
        LocalAddr: localAddr, // Set the desired local IP address here
        DualStack: true,
    }).DialContext,
    MaxIdleConns:          100,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 1 * time.Second,
}

// Create an HTTP client using the custom transport
client := &http.Client{
    Transport: transport,
}
Copy after login

By setting the LocalAddr field of the Dialer, you can specify the source IP address to be used for HTTP requests made by the client.

The above is the detailed content of How to Customize the Source IP Address for HTTP Requests in Go?. 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