# Go 代理接入示例

使用 net/http、环境变量、Transport 和请求超时完成 HTTP 代理访问。

Go 标准库可以通过 `http.Transport.Proxy` 使用 HTTP 代理。`PROXY_URL` 从受控环境注入，代码不保存明文凭据。

## Go

```go
package main

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

func main() {
  proxyURL, err := url.Parse(os.Getenv("PROXY_URL"))
  if err != nil { panic(err) }

  transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)}
  client := &http.Client{Transport: transport, Timeout: 30 * time.Second}
  response, err := client.Get("https://<public-test-host>/ip")
  if err != nil { panic(err) }
  defer response.Body.Close()
  fmt.Println(response.StatusCode)
}
```

## 配置

- 使用 `url.Parse` 解析代理 URL 并处理错误。
- 不要把解析后的 URL 输出到日志。

## 连接

- 设置客户端整体超时。
- 响应结束后关闭 Body。

## 复用

- 相同代理身份复用 Transport。
- 配置变化时关闭空闲连接。

## 错误处理

- 区分配置解析、网络错误和目标状态。
- 生产代码为 DNS、拨号和 TLS 增加分层指标。

html pre.shiki code .szBVR, html code.shiki .szBVR{--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sScJk, html code.shiki .sScJk{--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .sVt8B, html code.shiki .sVt8B{--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sZZnC, html code.shiki .sZZnC{--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .sj4cs, html code.shiki .sj4cs{--shiki-default:#005CC5;--shiki-dark:#79B8FF}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}
