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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 09:54:30294browse

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

Customizing HTTP Requests: Setting the Source IP Address

Question:

How can I specify the source IP address used for an HTTP request in Go?

Answer:

Although the standard library does not directly provide a way to set the source IP address for HTTP requests, you can achieve this by customizing the client's transport using a custom dialer.

Using a Custom Dialer

To customize the source IP address, you can create a custom dialer and assign it to the client's transport. Here's an example:

import (
    "net"
    "time"

    "golang.org/x/net/http/httpproxy"
)

// Create a custom transport with a specified local address
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 the client with the customized transport
client := &http.Client{
    Transport: transport,
}

By setting LocalAddr in the dialer, you can specify the source IP address to be used for the HTTP request.

Sample Usage

Once you have created the custom client, you can use it to make HTTP requests:

resp, err := client.Get("http://example.com/")
if err != nil {
    // handle error
}
defer resp.Body.Close()
// ...

This usage is similar to making requests using the standard http.Get, but it allows you to control the source IP address for the request. Remember to replace localAddr with the desired IP address.

The above is the detailed content of How to Specify the Source IP Address for HTTP Requests 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