如何设置哪个IP用于HTTP请求? [英] How to set which IP to use for a HTTP request?

查看:150
本文介绍了如何设置哪个IP用于HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有可能,因为std lib没有说明当前正在使用的地址:

org / pkg / net / http /rel =noreferrer> http://golang.org/pkg/net/http/ $ b

  resp,err:= http.Get(http://example.com/)
if err!= nil {
//处理错误
}
defer resp.Body.Close()
body,err:= ioutil.ReadAll(resp.Body)

我想要做的是设置该http请求的源地址,为什么?因为我不想使用我的主要IP地址的那种东西...

解决方案

您可以设置自定义拨号程序在客户端的传输中。

  //创建一个像http.DefaultTransport这样的传输,但是使用指定的localAddr 
传输:=& http.Transport {
Proxy:http.ProxyFromEnvironment,
DialContext:(& net.Dialer {
超时: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 {
运输:运输,
}


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...

解决方案

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,
}

这篇关于如何设置哪个IP用于HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆