go通过http代理访问

走代理时会做SNAT,改变源IP和源端口。

package main

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

func main() {
	// 国内代理
	proxyStr := "http://39.175.75.144:30001"
	proxyURL, err := url.Parse(proxyStr)
	if err != nil {
		fmt.Printf("parse proxy str failed, err is %v", err)
		return
	}

	// 创建客户端
	client := &http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyURL(proxyURL),
			// 配置代理认证鉴权
			// ProxyConnectHeader: ,
		},
		// 可选超时设置
		Timeout: 3 * time.Second,
	}

	resp, err := client.Get("http://myip.ipip.net")
	if err != nil {
		fmt.Printf("get failed, err is %v", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("read resp body failed, err is %v", err)
		return
	}
	fmt.Println(string(body))
}

image

静态代理配置通过Proxy和ProxyConnectHeader字段指定。
动态代理配置通过Proxy函数(指定代理URL)和GetProxyConnectHeader函数(指定代理请求头)指定。

posted on 2025-05-12 07:45  王景迁  阅读(21)  评论(0)    收藏  举报

导航