[Golang]开启本地代理下Golang进行Http请求

当本地开启软件的时候,明明浏览器可以访问,但是用golang的http包却不能访问,为什么会这样尼,其实golang的http走网络7层模型中偏下层,没有走位于上层软件的代理接口,因此golang的http无法访问,那么如何使用软件接口尼?需要配置下proxyURL, err := url.Parse(“http://127.0.0.1:10871”)其中的协议一般为http(也可以是socks)ip地址127.0.0.1不用改,端口按照实际的接口修改。


package main

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

func main() {
	// 创建一个代理地址
	proxyURL, err := url.Parse("http://127.0.0.1:10871")
	if err != nil {
		log.Fatal(err)
	}

	// 创建一个 Transport 实例,并配置代理
	transport := &http.Transport{
		Proxy: http.ProxyURL(proxyURL),
	}

	// 使用自定义的 Transport 实例创建一个 http.Client
	client := &http.Client{
		Transport: transport,
	}
	req, err := http.NewRequest("GET", "https://www.sehuatang.org", nil)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36")
	req.Header.Set("Cookie", "_safe=vqd37pjm4p5uodq339yzk6b7jdt6oich; cPNj_2132_saltkey=a5ffFKLd; cPNj_2132_lastvisit=1691752561; cPNj_2132_atarget=1; cPNj_2132_lastfp=6a9c7553e07b9f17e0dfa4f579361059; cPNj_2132_home_diymode=1; cPNj_2132_st_p=0%7C1692189681%7Cda20216937156c4d30b129e0d1859b42; cPNj_2132_viewid=tid_1493743; cPNj_2132_visitedfid=2D141D95D103D155D50D104D125D137D117; cPNj_2132_st_t=0%7C1692237351%7C5d8bcdb21881240dea376ba85b69c733; cPNj_2132_forum_lastvisit=D_152_1689677645D_142_1689771242D_139_1691155745D_37_1691493914D_41_1691756168D_154_1691756172D_36_1691773699D_43_1691773703D_48_1691773707D_49_1691773720D_165_1691773721D_96_1691774864D_145_1691817372D_146_1691829223D_155_1691835420D_109_1691836159D_143_1691836161D_103_1691911090D_117_1691927224D_137_1691927238D_125_1691927977D_104_1691927989D_50_1692067574D_95_1692194604D_141_1692237349D_2_1692237351; cPNj_2132_lastact=1692261728%09index.php%09")

	// 发起 HTTP 请求
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Response:", string(body))
}

你可能感兴趣的:(golang,http,开发语言)