英文:
Specify network interface for http request in Golang
问题
我正在使用Go的http包来进行HTTP请求。
在Ubuntu Linux上有多个接口时,我该如何配置Go的HTTP客户端以使用特定的接口或IP地址进行请求?
默认的HTTP客户端是如何决定使用哪个接口的?
英文:
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?
答案1
得分: 8
Go的http.Client
使用http.RoundTripper
进行请求。而http.RoundTripper
则使用net.Dialer
来建立出站网络连接。net.Dialer
有一个字段LocalAddr
,用于指定建立连接时使用的本地地址。你可以使用自己的Client
,自己的RoundTripper
和自己的net.Dialer
,并指定你想要使用的LocalAddr
。你可以从文档中链接的stdlib代码中查看每个实例是如何创建的,并复制用于创建默认实例的机制,以在需要时保持默认行为并覆盖LocalAddr
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论