前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang 强制对特定 ip 的 http 请求(类似于 curl --resolve)

golang 强制对特定 ip 的 http 请求(类似于 curl --resolve)

原创
作者头像
IT工作者
发布2023-11-17 11:03:22
3020
发布2023-11-17 11:03:22
举报
文章被收录于专栏:程序技术知识程序技术知识

如何强制 golang https get 请求使用特定的 IP 地址。我想跳过 DNS 解析并自己提供 IP。 curl 中的等价物是 --resolve,

curl https://domain.com/dir/filename --resolve "domain.com:443:10.10.10.10"

由于这是 ssl,因此我想避免用 IP 代替域,如下例所示。

curl https://10.10.10.10/dir/filename --header "主机:domain.com"

您可以提供自定义 Transport.DialContext功能。

代码语言:javascript
复制
func main() {
    dialer := &net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
        // DualStack: true, // this is deprecated as of go 1.16
    }
    // or create your own transport, there's an example on godoc.
    http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
        if addr == "google.com:443" {
            addr = "216.58.198.206:443"
        }
        return dialer.DialContext(ctx, network, addr)
    }
    resp, err := http.Get("https://google.com")
    log.Println(resp.Header, err)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档