英文:
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 := "<socket-path>"
// server
sock, err := net.Listen("unix", socket)
go http.Serve(s, nil)
//client
httpc := http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", socket)
},
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论