在Golang中指定HTTP请求的网络接口。

huangapple go评论84阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年6月15日 23:22:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/44571331.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定