Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set which IP to use for a HTTP request?

Tags:

go

I dont know if it's possible as the std lib does not state anything about the current address being used:

http://golang.org/pkg/net/http/

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

What I'm trying to do is set the source address for that http request, why? because I don't want to use my primary ip address for that kind of stuff...

like image 967
kainlite Avatar asked May 30 '15 23:05

kainlite


1 Answers

You can set a custom Dialer in the Client's Transport.

// 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,
        DualStack: true,
    }).DialContext,
    MaxIdleConns:          100,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 1 * time.Second,
}

client := &http.Client{
    Transport: transport,
}
like image 95
JimB Avatar answered Oct 19 '22 04:10

JimB