How to route http Get via tunnel in Go?

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

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

huangapple
  • 本文由 发表于 2015年11月13日 05:24:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/33681662.html
匿名

发表评论

匿名网友

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

确定