在Go语言中,可以使用代理/socks与http2客户端一起使用吗?

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

Is it possible to use proxy/socks with http2 client in Go?

问题

我发现,在http2包的实现中,不支持http2客户端的代理/socks。有没有简单的方法让它工作?

英文:

I found, implementation of transport in http2 package doesn't support proxy/socks for http2 client. Is there an simple way to make it work?

答案1

得分: 1

是的,我记得一段时间前有关于http2客户端与HTTP/SOCKS5代理不兼容的问题。不过现在时间已经过去了,下面的代码可以正常工作(如果你需要的话)。请注意,如果在Transport中使用自定义的DialTLS,代理连接仍然不受支持。

package main

import (
	"log"
	"net/http"
	"net/url"
)

func main() {
	var addressString = "https://www.facebook.com/"
	var proxyString = "socks5://127.0.0.1:9150"

	req, _ := http.NewRequest("GET", addressString, nil)
	tr := &http.Transport{
		Proxy: func(req *http.Request) (*url.URL, error) {
			proxyURI, err := url.Parse(proxyString)
			return proxyURI, err
		},
	}

	// http客户端已经准备好处理http/2连接
	hc := &http.Client{Transport: tr}
	resp, _ := hc.Do(req)
	log.Print(resp)
}

希望对你有帮助!

英文:

Yes I seem to recall something a while ago about the http2 client not working with HTTP/SOCKS5 proxies. Anyway time has moved on and the below works fine (if that's what you're after). Note that if using a custom DialTLS within the Transport, proxied connections still aren't supported.

package main

import (
	"log"
	"net/http"
	"net/url"
)

func main() {
	var addressString = "https://www.facebook.com/"
	var proxyString = "socks5://127.0.0.1:9150"

	req, _ := http.NewRequest("GET", addressString, nil)
	tr := &http.Transport{
		Proxy: func(req *http.Request) (*url.URL, error) {
			proxyURI, err := url.Parse(proxyString)
			return proxyURI, err
		},
	}

   // The http client is equipped to handle http/2 connections
	hc := &http.Client{Transport: tr}
	resp, _ := hc.Do(req)
	log.Print(resp)
}

答案2

得分: -1

如果你想通过套接字进行通信,可以使用以下代码:

socket := "<socket-path>"
// 服务器端
sock, err := net.Listen("unix", socket)
go http.Serve(sock, nil)

// 客户端
httpc := http.Client{
    Transport: &http.Transport{
        DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
            return net.Dial("unix", socket)
        },
    },
}

这段代码实现了通过套接字进行通信的功能。服务器端使用net.Listen函数监听指定的套接字路径,然后使用http.Serve函数处理传入的请求。客户端使用http.Client创建一个HTTP客户端,其中的DialContext函数用于建立与服务器的套接字连接。

英文:

If you're looking to communicate over sockets something like this should work:

socket := &quot;&lt;socket-path&gt;&quot;
// server
sock, err := net.Listen(&quot;unix&quot;, socket)
go http.Serve(s, nil)

//client
httpc := http.Client{
    Transport: &amp;http.Transport{
        DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
            return net.Dial(&quot;unix&quot;, socket)
        },
    },
}

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

发表评论

匿名网友

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

确定