英文:
How to route http Get via tunnel in Go?
问题
我有一个通过端口9998的SSH隧道连接到我的服务器。我希望在Go语言中将我的HTTP GET/POST请求路由到该端口。在Java中,我会指定DsocksProxyHost和DsocksProxyPort。我正在寻找Go语言中类似的选项。提前感谢您的帮助。
英文:
I have a ssh tunnel to my server (via port: 9998). I want my http GET/POST requests to be routed through this port in Go. In java I would specify the DsocksProxyHost and DsocksProxyPort. I am looking for a similar option in Go. Thank you for the help in advance.
答案1
得分: 3
使用上述评论中提供的信息,以下是如何通过SOCKS代理隧道传输HTTP请求的工作示例:
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
"golang.org/x/net/proxy"
)
func main() {
url := "https://example.com"
socksAddress := "localhost:9998"
socks, err := proxy.SOCKS5("tcp", socksAddress, nil, &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
})
if err != nil {
panic(err)
}
client := &http.Client{
Transport: &http.Transport{
Dial: socks.Dial,
TLSHandshakeTimeout: 10 * time.Second,
},
}
res, err := client.Get(url)
if err != nil {
panic(err)
}
content, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
panic(err)
}
fmt.Printf("%s", string(content))
}
希望对你有帮助!
英文:
Using the information provided in the above comments, here is a working example on how to tunnel HTTP requests through a SOCKS proxy:
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
"golang.org/x/net/proxy"
)
func main() {
url := "https://example.com"
socksAddress := "localhost:9998"
socks, err := proxy.SOCKS5("tcp", socksAddress, nil, &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
})
if err != nil {
panic(err)
}
client := &http.Client{
Transport: &http.Transport{
Dial: socks.Dial,
TLSHandshakeTimeout: 10 * time.Second,
},
}
res, err := client.Get(url)
if err != nil {
panic(err)
}
content, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
panic(err)
}
fmt.Printf("%s", string(content))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论