# Golang

> 使用 Proxyman Automatic Setup 抓取 Go 应用的 HTTP/HTTPS 流量，支持 net/http、fasthttp、resty、gorequest、req 和 grequests。

## 1. 新的自动方案（macOS v5.17.0 或更高版本）✅ {#1-new-automatic-solution-macos-v5170-or-later-}

Proxyman macOS v5.17.0 或更高版本可以一键抓取 Golang 的 HTTP/HTTPS 流量。

* 一键方案：无需手动设置 HTTP 代理配置，也无需手动信任自签名证书。
* ✅ 支持众多 Go 网络库：net/http、fasthttp、resty、gorequest、req、grequests

### 使用方法： {#how-to-use}

1. 打开 Proxyman -> Setup Menu -> Automatic Setup
2. 选择常用的终端 -> 点击 “Open New Terminal” 按钮
3. 如有需要，请允许 AppleScript 的权限请求

![Proxyman Automatic Setup 窗口，列出 net/http、resty 等 Golang 库，并带有 Open New Terminal 按钮](https://proxyman.com/docs/assets/proxyman-automatic-setup-window.jpg)

_打开预配置的终端，拦截 Go 的 HTTPS 流量_

4. 随即会打开一个新的终端窗口 -> 在其中启动你的 Golang 后端服务或运行脚本 => Proxyman 会自动抓取所有流量。
5. 例如： 

```
$ go run main.go
```

6. Proxyman 会抓取来自 Go 的所有 HTTP/HTTPS 流量，包括 net/http

![终端中运行 go run main.go，旁边是 Proxyman 中显示的 net/http、fasthttp 和 resty 抓取请求](https://proxyman.com/docs/assets/CleanShot%202025-03-18%20at%2009.56.44%402x.jpg)

_抓取并拦截 Go net/http 的 HTTPS 流量_

* Go 示例代码：[https://github.com/ProxymanApp/golang-example](https://github.com/ProxymanApp/golang-example)

## 2. 旧方案（不推荐 ❌） {#2-old-solution-not-recommended-}

* Proxyman 无法抓取 Golang 服务器的任何 HTTP/HTTPS 流量。
* 原因是部分网络库（如 net/http）不遵循系统 HTTP 代理设置，因此流量不会经过 Proxyman 应用。

### 2.1 解决方案 {#21-solution}

#### net/http {#nethttp}

1. 将代理设置为 Proxyman，默认地址为 localhost 的 9090 端口
2. 让 Transport 信任 Proxyman 的自签名证书。否则，net/http 会拒绝该证书，并报 SSL 错误。

```go
package main

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

func main() {
	// Create a new HTTP client
	client := &http.Client{}

	// Configure the proxy
	proxyURL, err := url.Parse("http://localhost:9090")
	if err != nil {
		log.Fatal("Error parsing proxy URL:", err)
	}

	// Configure transport with proxy and TLS settings
	transport := &http.Transport{
		Proxy: http.ProxyURL(proxyURL),
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true, // This allows self-signed certificates
		},
	}

	// Set the transport for the client
	client.Transport = transport

	// Make a request
	resp, err := client.Get("https://example.com")
	if err != nil {
		log.Fatal("Error making request:", err)
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("Error reading response:", err)
	}

	// Print the response
	fmt.Printf("Status: %s\n", resp.Status)
	fmt.Printf("Body: %s\n", string(body))
}

```

## 了解更多 {#learn-more}

* [使用 Proxyman 抓取 Golang 的 HTTP/HTTPS 流量](https://proxyman.com/golang)（Proxyman 官网）
