首頁 > 後端開發 > Golang > 主體

如何以程式設計方式在 Go 中為自訂傳輸配置代理程式?

Linda Hamilton
發布: 2024-10-26 04:34:30
原創
558 人瀏覽過

How do I Programmatically Configure a Proxy for a Custom Transport in Go?

在自訂傳輸中使用代理:Go 程式解決方案

在Go 中,預設情況下,http.Client 使用系統的代理設定作為在HTTP_PROXY 和HTTPS_PROXY 等環境變數中配置。但是,此行為可能不會擴展到自訂傳輸。

使用 http.ProxyFromEnvironment 設定代理

要以程式設計方式為自訂傳輸設定代理,您可以使用http.ProxyFromEnvironment 方法。此方法根據環境變數傳回代理 URL,HTTPS_PROXY 優先用於 HTTPS 請求。

<code class="go">import (
  "log"
  "net/http"
  "os"
)

func main() {
  // Get proxy URL from environment variables
  proxyURL := http.ProxyFromEnvironment(os.Getenv)

  // Create a custom transport
  transport := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    Proxy:           proxyURL,
  }

  // Create a client with the custom transport
  client := &http.Client{Transport: transport}

  // Send a request through the proxy
  resp, err := client.Get("https://example.com")
  if err != nil {
    log.Fatal("Error making request:", err)
  }

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

  // Print the response body
  fmt.Println(string(body))
}</code>
登入後複製

此程式碼片段示範如何使用 http.ProxyFromEnvironment 來設定自訂傳輸的代理程式。透過使用環境變數來配置代理設置,您可以輕鬆地在不同的代理配置之間切換,而無需修改程式碼。

以上是如何以程式設計方式在 Go 中為自訂傳輸配置代理程式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!