Making HTTP requests from different server IPs

563 views
Skip to first unread message

Julian

unread,
Jun 1, 2012, 12:47:48 PM6/1/12
to golang-nuts
Hi,

My server has multiple IPs and I want to specify the outgoing
interface (IP) to use when making a HTTP request. I have read from the
http package and I couldn't find anything of this sort.

I suppose I could do this with curl (go-curl)...

ch.Setopt(curl.OPT_INTERFACE, ip)

But I wanted to do it with go's own packages. Any ideas?

Brad Fitzpatrick

unread,
Jun 1, 2012, 9:54:13 PM6/1/12
to dmit, golan...@googlegroups.com
I'm glad http.Transport.Dial finds another good use.

And I totally agree with the comment: you want to re-use http.Clients.

On Fri, Jun 1, 2012 at 2:22 PM, dmit <dmit...@gmail.com> wrote:
What you need is a way for http.Client to use a custom Dial() function based on net.DialTCP() which takes the local address as an argument. That can be done by overriding the default http.Transport:

Would something like that work for you?

Julian

unread,
Jun 2, 2012, 4:29:47 AM6/2/12
to golang-nuts
Thanks for your answer. At first glance the code looks good, but
unfortunately it doesn't work :(

When getting a page from localhost or 127.0.0.1 (just like in your
code) I get the following error:
panic: Get http://127.0.0.1:80: dial tcp 127.0.0.1:80: cannot assign
requested address

When getting a page from a remote server (yes I have tried several) I
get the following error:
panic: Get http://www.google.com/: dial tcp 173.194.39.84:80: invalid
argument


On Jun 2, 12:22 am, dmit <dmitr...@gmail.com> wrote:
> What you need is a way for http.Client to use a custom Dial() function
> based on net.DialTCP() which takes the local address as an argument. That
> can be done by overriding the default http.Transport:http://play.golang.org/p/iTBLLk4YhL
>
> Would something like that work for you?
>
>
>
>
>
>
>
> On Friday, June 1, 2012 7:47:48 PM UTC+3, Julian wrote:
>

DisposaBoy

unread,
Jun 2, 2012, 7:31:16 AM6/2/12
to golan...@googlegroups.com


On Saturday, June 2, 2012 9:29:47 AM UTC+1, Julian wrote:
Thanks for your answer. At first glance the code looks good, but
unfortunately it doesn't work :(

When getting a page from localhost or 127.0.0.1 (just like in your
code) I get the following error:
panic: Get http://127.0.0.1:80: dial tcp 127.0.0.1:80: cannot assign
requested address

When getting a page from a remote server (yes I have tried several) I
get the following error:
panic: Get http://www.google.com/: dial tcp 173.194.39.84:80: invalid
argument


You're probably not using the correct ip address. where the actual *external* ip address as seen by e.g. your router is 1.2.3.4 that's the ip address you need to use. the port can simply be set to 0 so you end up with CustomClient("1.2.3.4:0").
Reply all
Reply to author
Forward
0 new messages