[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-post-cn-go-yuyan-shiyong-daili":3},{"success":4,"payload":5,"related":83,"errors":153},true,{"id":6,"slug":7,"title":8,"excerpt":9,"body_html":10,"meta_title":11,"meta_description":12,"canonical_url":13,"canonical_override":14,"og_title":8,"og_description":12,"og_image_url":15,"faq_json":16,"key_takeaways":32,"allow_index":38,"noindex_google_only":38,"allow_follow":4,"published_at":39,"updated_at":40,"content_updated_at":41,"featured_image_url":42,"featured_image_alt":14,"card_image_url":43,"reading_time_minutes":44,"author":45,"categories":49,"tags":56,"alternates":69,"locale_paths":81,"views":82},6,"go-yuyan-shiyong-daili","在Go语言中使用代理：HTTP客户端与SDK指南","使用 net\u002Fhttp 和 代理Hat Go SDK 来学习如何配置 Go 中的代理 。 包括认证、旋转、地理目标、goroutine货币和生产最佳做法.","\u003Ch2>为什么在 Go 中使用代理？\u003C\u002Fh2>\n\u003Cp>Go 已成为高性能网络工具、网页抓取器和 API 客户端的首选语言。其轻量级 goroutine、内置并发原语以及久经考验的 \u003Ccode>net\u002Fhttp\u003C\u002Fcode> 标准库，使其成为需要处理数千个并发请求的代理驱动应用的理想选择。\u003C\u002Fp>\n\u003Cp>无论你是在构建 \u003Ca href=\"\u002Fcn\u002Fuse-cases\u002Fweb-scraping\">网页抓取\u003C\u002Fa> 流水线、监控 \u003Ca href=\"\u002Fcn\u002Fuse-cases\u002Fserp-tracking\">SERP 排名\u003C\u002Fa>，还是收集竞品定价数据，让 Go HTTP 客户端通过代理路由都能让你轮换 IP 地址、绕过地理限制，并在大规模下避免速率限制。\u003C\u002Fp>\n\u003Cp>在本指南中，你将仅使用标准库让 Go 流量通过 ProxyHat 路由，并使用 \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fgo-sdk\" rel=\"noopener noreferrer\">ProxyHat Go SDK\u003C\u002Fa> 处理账户侧事务：查询位置代码和检查子用户流量。每个代码片段都可直接复制粘贴，并已针对实时网关运行验证。\u003C\u002Fp>\n\u003Ch2>安装\u003C\u002Fh2>\n\u003Ch3>仅使用标准库\u003C\u002Fh3>\n\u003Cp>通过代理发送请求只需 Go 的 \u003Ccode>net\u002Fhttp\u003C\u002Fcode> 和 \u003Ccode>net\u002Furl\u003C\u002Fcode> 包，无需额外安装。\u003C\u002Fp>\n\u003Ch3>ProxyHat Go SDK\u003C\u002Fh3>\n\u003Cp>该 SDK 是 ProxyHat 账户 API 的客户端：子用户、位置代码、使用量分析。它本身不发送你的 HTTP 请求；你的流量始终通过 \u003Ccode>net\u002Fhttp\u003C\u002Fcode>，如下所示。\u003C\u002Fp>\n\u003Cpre>\u003Ccode>go get github.com\u002FProxyHatCom\u002Fgo-sdk\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>认证与基本设置\u003C\u002Fh2>\n\u003Cp>ProxyHat 通过代理端点使用用户名-密码认证。你可以在 ProxyHat 仪表盘中找到子用户的代理凭据（详情请参阅 \u003Ca href=\"https:\u002F\u002Fdocs.proxyhat.com\u002F\" rel=\"noopener noreferrer\">文档\u003C\u002Fa>）。典型的代理 URL 如下所示：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>http:\u002F\u002FUSERNAME:PASSWORD@gate.proxyhat.com:8080\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>不要将凭据硬编码在源代码中。请使用环境变量或 \u003Ccode>.env\u003C\u002Fcode> 文件：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>export PROXYHAT_USER=\"your_username\"\nexport PROXYHAT_PASS=\"your_password\"\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>使用代理的简单 GET 请求\u003C\u002Fh2>\n\u003Cp>以下是仅使用标准库的最小实现：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>package main\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"net\u002Fhttp\"\n    \"net\u002Furl\"\n    \"os\"\n)\nfunc main() {\n    proxyURL, err := url.Parse(fmt.Sprintf(\n        \"http:\u002F\u002F%s:%s@gate.proxyhat.com:8080\",\n        os.Getenv(\"PROXYHAT_USER\"),\n        os.Getenv(\"PROXYHAT_PASS\"),\n    ))\n    if err != nil {\n        log.Fatal(err)\n    }\n    client := &http.Client{\n        Transport: &http.Transport{\n            Proxy: http.ProxyURL(proxyURL),\n        },\n    }\n    resp, err := client.Get(\"https:\u002F\u002Fhttpbin.org\u002Fip\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer resp.Body.Close()\n    body, _ := io.ReadAll(resp.Body)\n    fmt.Println(string(body))\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>运行后你会看到住宅 IP 地址而非你自己的 IP。每个请求都通过 ProxyHat 的 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fzhuzhai-vs-shujuzhongxin-vs-yidong-daili\">住宅代理池\u003C\u002Fa> 路由。\u003C\u002Fp>\n\u003Ch2>使用不同的代理类型\u003C\u002Fh2>\n\u003Cp>ProxyHat 支持两种轮换代理类型（数据中心代理即将推出），各自适用于不同的工作负载。你在同一端口上通过用户名标志选择类型（住宅为默认）：\u003C\u002Fp>\n\u003Ctable>\n\u003Ccaption>使用不同的代理类型\u003C\u002Fcaption>\n\u003Cthead>\n\u003Ctr>\u003Cth>类型\u003C\u002Fth>\u003Cth>用户名标志\u003C\u002Fth>\u003Cth>最适合\u003C\u002Fth>\u003Cth>平均延迟\u003C\u002Fth>\u003C\u002Ftr>\n\u003C\u002Fthead>\n\u003Ctbody>\n\u003Ctr>\u003Ctd>住宅\u003C\u002Ftd>\u003Ctd>无（默认）\u003C\u002Ftd>\u003Ctd>网页抓取、广告验证\u003C\u002Ftd>\u003Ctd>~800 ms\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>数据中心\u003C\u002Ftd>\u003Ctd>即将推出\u003C\u002Ftd>\u003Ctd>高速批量请求\u003C\u002Ftd>\u003Ctd>~200 ms\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>移动\u003C\u002Ftd>\u003Ctd>\u003Ccode>-type-mobile\u003C\u002Fcode>\u003C\u002Ftd>\u003Ctd>社交媒体、应用测试\u003C\u002Ftd>\u003Ctd>~1200 ms\u003C\u002Ftd>\u003C\u002Ftr>\n\u003C\u002Ftbody>\n\u003C\u002Ftable>\n\u003Cp>关于何时使用每种类型的更深入比较，请参阅我们的 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fzhuzhai-vs-shujuzhongxin-vs-yidong-daili\">住宅 vs 数据中心 vs 移动代理\u003C\u002Fa> 指南。\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F\u002F Same host and port for every type: the username selects it\nuser, pass := os.Getenv(\"PROXYHAT_USER\"), os.Getenv(\"PROXYHAT_PASS\")\nresidential := fmt.Sprintf(\"http:\u002F\u002F%s:%s@gate.proxyhat.com:8080\", user, pass)\nmobile := fmt.Sprintf(\"http:\u002F\u002F%s-type-mobile:%s@gate.proxyhat.com:8080\", user, pass)\n\u002F\u002F datacenter: coming soon at ProxyHat\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>为代理配置 http.Transport\u003C\u002Fh2>\n\u003Cp>如需完全控制，可直接配置 \u003Ccode>http.Transport\u003C\u002Fcode>。这让你可以调整连接池、TLS 设置和超时：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>package main\nimport (\n    \"crypto\u002Ftls\"\n    \"net\u002Fhttp\"\n    \"net\u002Furl\"\n    \"time\"\n)\nfunc newProxyClient(proxyAddr string) (*http.Client, error) {\n    proxyURL, err := url.Parse(proxyAddr)\n    if err != nil {\n        return nil, err\n    }\n    transport := &http.Transport{\n        Proxy:               http.ProxyURL(proxyURL),\n        MaxIdleConns:        100,\n        MaxIdleConnsPerHost: 10,\n        IdleConnTimeout:     90 * time.Second,\n        TLSClientConfig:     &tls.Config{MinVersion: tls.VersionTLS12},\n    }\n    client := &http.Client{\n        Transport: transport,\n        Timeout:   30 * time.Second,\n    }\n    return client, nil\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>使用 ProxyHat Go SDK 查询位置和使用量\u003C\u002Fh2>\n\u003Cp>\u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fgo-sdk\" rel=\"noopener noreferrer\">ProxyHat Go SDK\u003C\u002Fa> 使用你的 API 密钥与账户 API 通信。在抓取器中有两件事很方便：查找用于地理定位的精确区域和城市代码，以及检查每个子用户已使用的流量。\u003C\u002Fp>\n\u003Cpre>\u003Ccode>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n\n    proxyhat \"github.com\u002FProxyHatCom\u002Fgo-sdk\"\n)\n\nfunc main() {\n    client := proxyhat.NewClient(os.Getenv(\"PROXYHAT_API_KEY\"))\n    ctx := context.Background()\n\n    \u002F\u002F City codes for geo-targeting. A city always needs its region.\n    country, region := \"us\", \"new_york\"\n    cities, err := client.Locations.Cities(ctx, &amp;proxyhat.CityParams{\n        RegionParams: proxyhat.RegionParams{CountryCode: &amp;country},\n        RegionCode:   &amp;region,\n    })\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, c := range cities {\n        fmt.Printf(\"%-20s -country-%s-region-%s-city-%s\\n\", c.Name, country, region, c.Code)\n    }\n\n    \u002F\u002F Traffic used by each sub-user\n    users, err := client.SubUsers.List(ctx)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, u := range users {\n        fmt.Println(u.ProxyUsername, u.LifecycleStatus, \"used:\", u.UsedTraffic)\n    }\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>SDK 返回类型化结构体和 API 错误。完整方法参考请查看 \u003Ca href=\"https:\u002F\u002Fdocs.proxyhat.com\u002F\" rel=\"noopener noreferrer\">API 文档\u003C\u002Fa>。\u003C\u002Fp>\n\u003Ch2>轮换会话 vs 粘性会话\u003C\u002Fh2>\n\u003Cp>ProxyHat 支持两种会话模式：\u003C\u002Fp>\n\u003Cul>\n\u003Cli>\u003Cstrong>轮换（默认）\u003C\u002Fstrong> &mdash; 每个新连接获得新 IP。适用于大规模 \u003Ca href=\"\u002Fcn\u002Fuse-cases\u002Fweb-scraping\">网页抓取\u003C\u002Fa>。\u003C\u002Fli>\n\u003Cli>\u003Cstrong>粘性\u003C\u002Fstrong> &mdash; 在你于用户名中设置的时长内保持同一 IP（从一分钟到 24 小时）。适用于登录序列或分页爬取等多步骤流程。\u003C\u002Fli>\n\u003C\u002Ful>\n\u003Ch3>轮换会话\u003C\u002Fh3>\n\u003Cp>Go 默认复用连接，而复用的隧道会保持相同的出口 IP。要让每个请求都获得新 IP，请关闭 keep-alive：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>proxyURL := &amp;url.URL{\n    Scheme: \"http\",\n    User:   url.UserPassword(os.Getenv(\"PROXYHAT_USER\"), os.Getenv(\"PROXYHAT_PASS\")),\n    Host:   \"gate.proxyhat.com:8080\",\n}\n\u002F\u002F No session flags = rotating. Turn keep-alive off so each request opens\n\u002F\u002F a new tunnel through the gateway and gets a new exit IP.\nclient := &amp;http.Client{\n    Transport: &amp;http.Transport{\n        Proxy:             http.ProxyURL(proxyURL),\n        DisableKeepAlives: true,\n    },\n    Timeout: 30 * time.Second,\n}\nfor i := 0; i &lt; 5; i++ {\n    resp, err := client.Get(\"https:\u002F\u002Fapi.ipify.org\")\n    if err != nil {\n        log.Println(err)\n        continue\n    }\n    ip, _ := io.ReadAll(resp.Body)\n    resp.Body.Close()\n    fmt.Printf(\"Request %d: %s\\n\", i+1, ip)\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>粘性会话\u003C\u002Fh3>\n\u003Cp>在用户名中添加会话 ID（8&ndash;32 个十六进制字符）和生命周期。所有使用相同 ID 的请求都从同一 IP 出口，直到生命周期结束：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F\u002F Sticky: -sid-&lt;hex id&gt;-ttl-&lt;duration&gt; keeps one exit IP for the session\nsid := make([]byte, 8)\nif _, err := rand.Read(sid); err != nil { \u002F\u002F crypto\u002Frand\n    log.Fatal(err)\n}\nusername := fmt.Sprintf(\"%s-country-us-sid-%x-ttl-10m\", os.Getenv(\"PROXYHAT_USER\"), sid)\nproxyURL := &amp;url.URL{\n    Scheme: \"http\",\n    User:   url.UserPassword(username, os.Getenv(\"PROXYHAT_PASS\")),\n    Host:   \"gate.proxyhat.com:8080\",\n}\nclient := &amp;http.Client{\n    Transport: &amp;http.Transport{Proxy: http.ProxyURL(proxyURL)},\n    Timeout:   30 * time.Second,\n}\n\u002F\u002F Every request through this client exits from the same IP for 10 minutes\nresp1, err := client.Get(\"https:\u002F\u002Fexample.com\u002Flogin\")\n\u002F\u002F ...\nresp2, err := client.Get(\"https:\u002F\u002Fexample.com\u002Faccount\")\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>每个 worker 一个会话\u003C\u002Fh3>\n\u003Cp>如果并行运行粘性会话，请为每个 goroutine 分配自己的会话 ID，而不是共享一个：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F\u002F One session ID per worker: a single sticky session is not meant\n\u002F\u002F to carry dozens of parallel connections\nfunc newSessionID() string {\n    b := make([]byte, 8)\n    rand.Read(b)\n    return hex.EncodeToString(b)\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>地理定位请求\u003C\u002Fh2>\n\u003Cp>需要来自特定国家的 IP？ProxyHat 支持 \u003Ca href=\"\u002Fcn\u002Flocations\">190+ 个位置\u003C\u002Fa>。将位置添加到用户名中；区域和城市代码来自位置 API（参见上面的 SDK 示例）：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>user := os.Getenv(\"PROXYHAT_USER\")\n\n\u002F\u002F Country only (ISO 3166-1 alpha-2, lower case)\nus := user + \"-country-us\"\n\n\u002F\u002F Region + city: the city code always follows its region code\nnyc := user + \"-country-us-region-new_york-city-new_york_city\"\n\n\u002F\u002F Mobile exit in Germany\ndeMobile := user + \"-country-de-type-mobile\"\n\n\u002F\u002F Build the proxy URL from any of them\nproxyURL := &amp;url.URL{\n    Scheme: \"http\",\n    User:   url.UserPassword(nyc, os.Getenv(\"PROXYHAT_PASS\")),\n    Host:   \"gate.proxyhat.com:8080\",\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>地理定位对于本地化 \u003Ca href=\"\u002Fcn\u002Fuse-cases\u002Fserp-tracking\">SERP 跟踪\u003C\u002Fa>、区域定价检查和内容可用性测试至关重要。\u003C\u002Fp>\n\u003Ch2>错误处理与重试\u003C\u002Fh2>\n\u003Cp>通过代理的网络请求可能因暂时性原因失败：连接重置、超时或临时封锁。健壮的错误处理对生产级抓取器至关重要。\u003C\u002Fp>\n\u003Ch3>哪些错误需要重试\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>\u002F\u002F retryable reports whether a failed request is worth repeating.\n\u002F\u002F \"Proxy Authentication Required\" (407) means wrong credentials or an\n\u002F\u002F unknown username flag: retrying the same request will not fix it.\nfunc retryable(resp *http.Response, err error) bool {\n    if err != nil {\n        return !strings.Contains(err.Error(), \"Proxy Authentication Required\")\n    }\n    return resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode &gt;= 500\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>使用指数退避的手动重试\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>package main\nimport (\n    \"fmt\"\n    \"math\"\n    \"net\u002Fhttp\"\n    \"time\"\n)\nfunc fetchWithRetry(client *http.Client, url string, maxRetries int) (*http.Response, error) {\n    var lastErr error\n    for attempt := 0; attempt &lt;= maxRetries; attempt++ {\n        resp, err := client.Get(url)\n        if err == nil &amp;&amp; resp.StatusCode &lt; 500 {\n            return resp, nil\n        }\n        if err != nil {\n            lastErr = err\n        } else {\n            lastErr = fmt.Errorf(\"HTTP %d\", resp.StatusCode)\n            resp.Body.Close()\n        }\n        backoff := time.Duration(math.Pow(2, float64(attempt))) * time.Second\n        time.Sleep(backoff)\n    }\n    return nil, fmt.Errorf(\"all %d retries failed: %w\", maxRetries, lastErr)\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>使用 Goroutine 进行并发抓取\u003C\u002Fh2>\n\u003Cp>Go 的并发模型是其超能力。借助 goroutine 和 channel，你可以并发抓取数百个 URL，同时保持内存占用极低。\u003C\u002Fp>\n\u003Cpre>\u003Ccode>package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"net\u002Fhttp\"\n    \"net\u002Furl\"\n    \"os\"\n    \"sync\"\n    \"time\"\n)\n\ntype Result struct {\n    URL        string\n    StatusCode int\n    Body       string\n    Err        error\n}\n\nfunc scrape(client *http.Client, urls []string, concurrency int) []Result {\n    results := make([]Result, len(urls))\n    sem := make(chan struct{}, concurrency) \u002F\u002F semaphore\n    var wg sync.WaitGroup\n    for i, u := range urls {\n        wg.Add(1)\n        go func(idx int, target string) {\n            defer wg.Done()\n            sem &lt;- struct{}{}        \u002F\u002F acquire\n            defer func() { &lt;-sem }() \u002F\u002F release\n            resp, err := client.Get(target)\n            if err != nil {\n                results[idx] = Result{URL: target, Err: err}\n                return\n            }\n            defer resp.Body.Close()\n            body, err := io.ReadAll(resp.Body)\n            results[idx] = Result{\n                URL:        target,\n                StatusCode: resp.StatusCode,\n                Body:       string(body),\n                Err:        err,\n            }\n        }(i, u)\n    }\n    wg.Wait()\n    return results\n}\n\nfunc main() {\n    proxyURL := &amp;url.URL{\n        Scheme: \"http\",\n        User:   url.UserPassword(os.Getenv(\"PROXYHAT_USER\"), os.Getenv(\"PROXYHAT_PASS\")),\n        Host:   \"gate.proxyhat.com:8080\",\n    }\n    client := &amp;http.Client{\n        Transport: &amp;http.Transport{\n            Proxy:               http.ProxyURL(proxyURL),\n            MaxIdleConnsPerHost: 20,\n        },\n        Timeout: 30 * time.Second,\n    }\n    urls := []string{\n        \"https:\u002F\u002Fexample.com\u002Fpage\u002F1\",\n        \"https:\u002F\u002Fexample.com\u002Fpage\u002F2\",\n        \"https:\u002F\u002Fexample.com\u002Fpage\u002F3\",\n        \u002F\u002F ... hundreds more\n    }\n    results := scrape(client, urls, 20)\n    for _, r := range results {\n        if r.Err != nil {\n            fmt.Printf(\"FAIL %s: %v\\n\", r.URL, r.Err)\n        } else {\n            fmt.Printf(\"OK   %s: %d bytes\\n\", r.URL, len(r.Body))\n        }\n    }\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>使用信号量进行速率限制\u003C\u002Fh2>\n\u003Cp>上面的抓取器已经使用信号量 channel 来限制并发。如需更细粒度的速率限制（例如每秒 N 个请求），请使用 \u003Ccode>golang.org\u002Fx\u002Ftime\u002Frate\u003C\u002Fcode>：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n    \"net\u002Fhttp\"\n    \"net\u002Furl\"\n    \"os\"\n    \"time\"\n\n    \"golang.org\u002Fx\u002Ftime\u002Frate\"\n)\n\nfunc main() {\n    proxyURL := &amp;url.URL{\n        Scheme: \"http\",\n        User:   url.UserPassword(os.Getenv(\"PROXYHAT_USER\"), os.Getenv(\"PROXYHAT_PASS\")),\n        Host:   \"gate.proxyhat.com:8080\",\n    }\n    client := &amp;http.Client{\n        Transport: &amp;http.Transport{Proxy: http.ProxyURL(proxyURL)},\n        Timeout:   30 * time.Second,\n    }\n    \u002F\u002F Allow 10 requests per second, burst of 20\n    limiter := rate.NewLimiter(10, 20)\n    urls := []string{\"https:\u002F\u002Fexample.com\u002F1\", \"https:\u002F\u002Fexample.com\u002F2\"}\n    for _, u := range urls {\n        if err := limiter.Wait(context.Background()); err != nil {\n            log.Fatal(err)\n        }\n        resp, err := client.Get(u)\n        if err != nil {\n            fmt.Printf(\"Error: %v\\n\", err)\n            continue\n        }\n        resp.Body.Close()\n        fmt.Printf(\"%s - %d\\n\", u, resp.StatusCode)\n    }\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>生产环境建议\u003C\u002Fh2>\n\u003Ch3>连接池\u003C\u002Fh3>\n\u003Cp>Go 的 \u003Ccode>http.Transport\u003C\u002Fcode> 默认维护空闲连接池。对于代理工作负载，请调整以下设置：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>transport := &http.Transport{\n    Proxy:                 http.ProxyURL(proxyURL),\n    MaxIdleConns:          200,\n    MaxIdleConnsPerHost:   50,\n    MaxConnsPerHost:       100,\n    IdleConnTimeout:       90 * time.Second,\n    ResponseHeaderTimeout: 15 * time.Second,\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>超时\u003C\u002Fh3>\n\u003Cp>始终设置超时。没有超时的抓取器最终会因连接停滞而挂起：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>client := &http.Client{\n    Transport: transport,\n    Timeout:   30 * time.Second, \u002F\u002F total request timeout\n}\n\u002F\u002F Or use context for per-request control\nctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\ndefer cancel()\nreq, _ := http.NewRequestWithContext(ctx, \"GET\", targetURL, nil)\nresp, err := client.Do(req)\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>优雅关闭\u003C\u002Fh3>\n\u003Cp>在长时间运行的抓取器中，监听操作系统信号以干净地关闭：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>package main\nimport (\n    \"context\"\n    \"os\"\n    \"os\u002Fsignal\"\n    \"syscall\"\n)\nfunc main() {\n    ctx, stop := signal.NotifyContext(\n        context.Background(),\n        os.Interrupt, syscall.SIGTERM,\n    )\n    defer stop()\n    \u002F\u002F Pass ctx to your scraping functions\n    \u002F\u002F When Ctrl+C is pressed, ctx is cancelled\n    \u002F\u002F and in-flight requests wind down gracefully\n    runScraper(ctx)\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>日志与可观测性\u003C\u002Fh3>\n\u003Cp>包装你的 HTTP transport 以记录请求耗时和状态码。这有助于在生产环境中识别慢目标和代理错误：\u003C\u002Fp>\n\u003Cpre>\u003Ccode>type loggingTransport struct {\n    inner http.RoundTripper\n}\nfunc (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n    start := time.Now()\n    resp, err := t.inner.RoundTrip(req)\n    elapsed := time.Since(start)\n    if err != nil {\n        log.Printf(\"ERR  %s %s (%v) err=%v\", req.Method, req.URL, elapsed, err)\n    } else {\n        log.Printf(\"OK   %s %s (%v) status=%d\", req.Method, req.URL, elapsed, resp.StatusCode)\n    }\n    return resp, err\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cblockquote>\n\u003Ch3>关键要点\u003C\u002Fh3>\n\u003Cul>\n\u003Cli>Go 的 goroutine + 代理 = 大规模并发。你可以以极低的内存开销运行数千个代理路由请求。\u003C\u002Fli>\n\u003Cli>\u003Cstrong>标准库就是你所需要的全部\u003C\u002Fstrong>，即可让流量通过 ProxyHat：在 \u003Ccode>http.Transport\u003C\u002Fcode> 上设置 \u003Ccode>Proxy\u003C\u002Fcode>，并将定位标志放入用户名中。\u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fgo-sdk\" rel=\"noopener noreferrer\">ProxyHat Go SDK\u003C\u002Fa> 涵盖账户 API（位置、子用户、使用量）。\u003C\u002Fli>\n\u003Cli>\u003Cstrong>使用轮换 IP\u003C\u002Fstrong> 进行大规模抓取（关闭 keep-alive 以让每个请求获得新 IP），\u003Cstrong>粘性会话\u003C\u002Fstrong> 用于登录流程等多步骤工作流。\u003C\u002Fli>\n\u003Cli>始终在 \u003Ccode>http.Client\u003C\u002Fcode> 上以及通过 \u003Ccode>context.WithTimeout\u003C\u002Fcode> 设置超时，以实现按请求控制。\u003C\u002Fli>\n\u003Cli>使用 \u003Ccode>golang.org\u002Fx\u002Ftime\u002Frate\u003C\u002Fcode> 负责任地限制速率，并使用信号量 channel 限制并发。\u003C\u002Fli>\n\u003Cli>在用户名中使用国家、区域和城市代码进行地理定位请求，以访问全球 \u003Ca href=\"\u002Fcn\u002Flocations\">190+ 个位置\u003C\u002Fa>。\u003C\u002Fli>\n\u003Cli>查看我们的 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fzuijia-wangluo-caiji-daili-2026\">最佳网页抓取代理\u003C\u002Fa> 指南，为你的工作负载选择合适的套餐。\u003C\u002Fli>\n\u003C\u002Ful>\n\u003C\u002Fblockquote>","Go语言代理使用指南：HTTP客户端与SDK","在Go语言中集成代理的完整指南。使用net\u002Fhttp客户端和ProxyHat Go SDK实现代理配置、IP轮换和SOCKS5连接的代码示例。","\u002Fcn\u002Fblog\u002Fgo-yuyan-shiyong-daili",null,"https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fgo-yuyan-shiyong-daili-og.webp",[17,20,23,26,29],{"question":18,"answer":19},"如何在 Go 的 net\u002Fhttp 客户端中配置代理？","将 http.Transport 的 Proxy 字段设置为 http.ProxyURL(parsedURL)，其中 parsedURL 是用 url.Parse() 解析的代理地址。然后将该 transport 传给 http.Client。标准库会自动为 HTTPS 目标处理 CONNECT 隧道。",{"question":21,"answer":22},"ProxyHat Go SDK 是做什么的？","它是 ProxyHat 账户 API 的类型化客户端：管理子用户、查询国家、区域和城市代码，以及读取使用量分析。代理流量本身通过 Go 的 net\u002Fhttp 使用网关 URL 传输，通过 CONNECT 隧道处理 HTTPS 目标，因此你的客户端与目标服务器之间的流量保持端到端加密。",{"question":24,"answer":25},"通过 Go 代理可以发起多少个并发请求？","Go 的 goroutine 极其轻量（每个栈约 4 KB），因此你可以并发运行数万个。实际限制是目标服务器的容量和你自己的速率限制。对于粘性会话，请为每个 worker 分配自己的会话 ID，而不是共享一个。使用信号量 channel 将并发限制在安全水平。",{"question":27,"answer":28},"轮换和粘性代理会话有什么区别？","轮换会话为每个请求分配新的 IP 地址，非常适合广泛抓取。粘性会话在你设置的时长内（从一分钟到 24 小时）保持同一 IP，适合目标期望一致访客的多步骤流程，例如登录序列或结账页面。",{"question":30,"answer":31},"如何在 Go 中处理代理错误和重试？","对超时、连接重置、429 和 5xx 响应使用指数退避重试：将请求包装在循环中，每次失败后延迟加倍。不要重试 407 Proxy Authentication Required：它意味着凭据错误或未知的用户名标志。对于粘性会话，如果同一 IP 持续失败，请切换到新的会话 ID。",[33,34,35,36,37],"Go 的并发和标准库使其成为构建高性能代理驱动的网页抓取器和 API 客户端的理想选择。","仅使用标准 net\u002Fhttp 库即可让 Go 流量通过 ProxyHat 路由；ProxyHat Go SDK 涵盖账户 API，例如位置代码和子用户使用量。","ProxyHat 提供住宅和移动代理（数据中心即将推出），在同一端口上通过用户名标志选择。","使用轮换会话进行大规模抓取，让每个请求获得新 IP；使用粘性会话处理登录等多步骤工作流。","对于生产级抓取器，请调整连接池、设置严格超时并实现优雅关闭以确保稳定性。",false,"2026-01-08T19:01:42+00:00","2026-07-19T03:13:07+00:00","2026-11-17T10:36:14+00:00","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fgo-yuyan-shiyong-daili-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fgo-yuyan-shiyong-daili-card.webp",13,{"name":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},"ProxyHat Team","proxyhat-team","The ProxyHat editorial team covers proxies, web scraping, and data extraction.",[50],{"id":51,"slug":52,"name":53,"description":14,"meta_title":54,"meta_description":55,"parent_id":14},4,"kaifa-zhinan","开发者指南","开发者指南 | ProxyHat 博客","代码教程和SDK指南，帮助您将代理集成到应用程序中。",[57,61,65],{"id":58,"slug":59,"name":60},1,"web-scraping","网页抓取",{"id":62,"slug":63,"name":64},11,"go","Go",{"id":66,"slug":67,"name":68},12,"sdk","SDK",{"tr":70,"ja":71,"de":72,"ru":73,"zh":13,"en":74,"fr":75,"pt":76,"it":77,"es":78,"ko":79,"pl":80,"x-default":74},"\u002Ftr\u002Fblog\u002Fgo-ile-proxy-kullanimi","\u002Fja\u002Fblog\u002Fgo-de-prokishi-wo-tsukau","\u002Fde\u002Fblog\u002Fproxies-in-go-verwenden","\u002Fru\u002Fblog\u002Fispolzovanie-proksi-v-go","\u002Fblog\u002Fusing-proxies-in-go","\u002Ffr\u002Fblog\u002Futiliser-des-proxies-en-go","\u002Fpt\u002Fblog\u002Fusando-proxies-em-go","\u002Fit\u002Fblog\u002Futilizzo-dei-proxy-in-go-guida-http-client-sdk","\u002Fes\u002Fblog\u002Fusar-proxies-en-go","\u002Fko\u002Fblog\u002Fgo-proxy-sayongbeop","\u002Fpl\u002Fblog\u002Fkorzystanie-z-proxies-in-go-http-client-sdk-guide",{"tr":70,"ja":71,"de":72,"ru":73,"zh":13,"en":74,"fr":75,"pt":76,"it":77,"es":78,"ko":79,"pl":80},81,[84,101,118,137],{"id":85,"slug":86,"title":87,"excerpt":88,"featured_image_url":89,"featured_image_alt":14,"card_image_url":90,"og_image_url":91,"published_at":92,"updated_at":40,"content_updated_at":93,"reading_time_minutes":66,"is_featured":38,"indexable":38,"views":94,"author":95,"categories":96,"tags":98},50,"sheji-kekaode-caiji-jiagou","设计可靠的网络爬虫架构","设计端到端的刮刮系统:排程器,URL队列,爬行器池,代理层,剖析器,存储,以及监控. 生产准备的 Python 代码与建筑图.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-og.webp","2026-02-24T06:55:16+00:00","2026-10-03T08:21:25+00:00",73,{"name":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},[97],{"id":51,"slug":52,"name":53,"description":14,"meta_title":54,"meta_description":55,"parent_id":14},[99,100],{"id":66,"slug":67,"name":68},{"id":58,"slug":59,"name":60},{"id":102,"slug":103,"title":104,"excerpt":105,"featured_image_url":106,"featured_image_alt":14,"card_image_url":107,"og_image_url":108,"published_at":109,"updated_at":40,"content_updated_at":110,"reading_time_minutes":62,"is_featured":38,"indexable":38,"views":111,"author":112,"categories":113,"tags":115},41,"jiankong-daili-xingneng","监控代理性能：延迟、成功率和告警","学习如何对代理性能进行仪表、监控和警报——跟踪延迟百分位数、成功率、错误模式和带宽。 Python、Node.js和Go的代码示例.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-og.webp","2026-02-15T00:39:23+00:00","2026-10-03T08:21:24+00:00",77,{"name":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},[114],{"id":51,"slug":52,"name":53,"description":14,"meta_title":54,"meta_description":55,"parent_id":14},[116,117],{"id":66,"slug":67,"name":68},{"id":58,"slug":59,"name":60},{"id":119,"slug":120,"title":121,"excerpt":122,"featured_image_url":123,"featured_image_alt":14,"card_image_url":124,"og_image_url":125,"published_at":126,"updated_at":40,"content_updated_at":127,"reading_time_minutes":128,"is_featured":38,"indexable":38,"views":85,"author":129,"categories":130,"tags":134},36,"kuozhan-caiji-jiagou","如何扩展网络爬虫基础设施","缩放网刮的架构模式:基于队列的系统,管道设计,带容器的横向缩放,以及规模化的代理管理. 代码在Python,Node.js,和去.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-og.webp","2026-02-09T14:42:34+00:00","2026-02-26T00:33:08+00:00",10,{"name":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},[131],{"id":58,"slug":59,"name":60,"description":14,"meta_title":132,"meta_description":133,"parent_id":14},"网页抓取指南 | ProxyHat 博客","网页抓取技术、代理策略和数据提取最佳实践。",[135,136],{"id":58,"slug":59,"name":60},{"id":66,"slug":67,"name":68},{"id":138,"slug":139,"title":140,"excerpt":141,"featured_image_url":142,"featured_image_alt":14,"card_image_url":143,"og_image_url":144,"published_at":145,"updated_at":40,"content_updated_at":110,"reading_time_minutes":66,"is_featured":38,"indexable":38,"views":146,"author":147,"categories":148,"tags":150},35,"kuozhan-daili-qingqiu-bingfa-kongzhi","使用并发控制扩展代理请求","用于代理式刮刮的主货币图案:Ayncio semaphores,承诺池,Go工人池,限速器,以及反压. Python、Node.js和Go的生产代码.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-og.webp","2026-02-08T11:16:13+00:00",362,{"name":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},[149],{"id":51,"slug":52,"name":53,"description":14,"meta_title":54,"meta_description":55,"parent_id":14},[151,152],{"id":66,"slug":67,"name":68},{"id":58,"slug":59,"name":60},[]]