2

I a using go's http package to make http requests. When having several interfaces on Ubuntu Linux, how can I configure go's http client to use a specific interface or IP address to perform the request?

How does the default http client decide which interface it uses?

alex
  • 2,252
  • 4
  • 23
  • 34
  • note that in linux you don't normally bind to an interface, you choose the IP address to bind to and the interface is chosen during routing. – JimB Jun 15 '17 at 15:42
  • 1
    Wanted to say that on Linux you actually can bind to interface via `SO_BINDTODEVICE`. I already provided some details in my [python response](https://stackoverflow.com/questions/48996494/send-http-request-through-specific-network-interface/68906789#68906789). And binding to IP is not always works as binding to interface (cause it still can route traffic through other interfaces). Here's [golang example](https://gist.github.com/bacher09/51ce161105a9e1f49b8b917f8eccd3c5). – Slava Bacherikov Aug 24 '21 at 12:25

1 Answers1

8

Go's http.Client makes requests using a http.RoundTripper. This, in turn, uses a net.Dialer to establish the outbound network connections. net.Dialer has a field LocalAddr which specifies the local address from which the connections will be made. You can use your own Client, with your own RoundTripper, with your own net.Dialer, specifying the LocalAddr you want to use. You can see how each of these is instantiated in the stdlib code linked from the documentation, and copy the mechanisms used to create the default instances to maintain default behavior while overriding the LocalAddr as needed.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • Hi, that's the response however, I personally always like to see an example, that may be obvious for some, not for others, or if you don't have an example in hand try pointing to some link that has, I am gonna do it now: https://gist.github.com/2minchul/191716b3ca8799f53362746731d08e91 – Melardev Sep 19 '21 at 10:40