Home > Backend Development > Golang > How Can I Specify a Custom Source IP Address for HTTP Requests in Go?

How Can I Specify a Custom Source IP Address for HTTP Requests in Go?

Susan Sarandon
Release: 2024-12-17 17:56:14
Original
834 people have browsed it

How Can I Specify a Custom Source IP Address for HTTP Requests in Go?

Customizing IP Selection for HTTP Requests

The standard library for HTTP requests in Go does not explicitly specify the source IP address used for outgoing requests. This raises the question: can we manually specify the IP address for such requests?

Solution

Yes, we can set a custom Dialer in the Client's Transport to control the IP address used for HTTP requests. Here's how:

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

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

By assigning a LocalAddr to the Dialer, you can specify the source IP address that will be used for HTTP requests made through that client. This allows you to control the IP address that will be exposed to the destination server, providing flexibility in managing IP reputation or routing considerations.

The above is the detailed content of How Can I Specify a Custom 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