From b4a99929d860c4f7961b1c9e16243c583c49238a Mon Sep 17 00:00:00 2001 From: shawnfinelee <15016051+shawnfinelee@users.noreply.github.com> Date: Thu, 18 May 2023 00:02:29 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81http=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.dev.json | 3 ++- config/config.go | 6 ++++++ gtp/gtp.go | 18 +++++++++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/config.dev.json b/config.dev.json index b78e4db..fe57546 100644 --- a/config.dev.json +++ b/config.dev.json @@ -1,4 +1,5 @@ { "api_key": "your api key", - "auto_pass": true + "auto_pass": true, + "proxy_url": "" } diff --git a/config/config.go b/config/config.go index 6afede1..7a502a3 100644 --- a/config/config.go +++ b/config/config.go @@ -13,6 +13,8 @@ type Configuration struct { ApiKey string `json:"api_key"` // 自动通过好友 AutoPass bool `json:"auto_pass"` + // 代理地址 + ProxyURL string `json:"proxy_url"` } var config *Configuration @@ -39,12 +41,16 @@ func LoadConfig() *Configuration { // 如果环境变量有配置,读取环境变量 ApiKey := os.Getenv("ApiKey") AutoPass := os.Getenv("AutoPass") + HttpProxy := os.Getenv("HTTP_PROXY") if ApiKey != "" { config.ApiKey = ApiKey } if AutoPass == "true" { config.AutoPass = true } + if HttpProxy != "" { + config.ProxyURL = HttpProxy + } }) return config } diff --git a/gtp/gtp.go b/gtp/gtp.go index 15cd8e2..8ff1df7 100644 --- a/gtp/gtp.go +++ b/gtp/gtp.go @@ -3,10 +3,12 @@ package gtp import ( "bytes" "encoding/json" - "github.com/869413421/wechatbot/config" "io/ioutil" "log" "net/http" + "net/url" + + "github.com/869413421/wechatbot/config" ) const BASEURL = "https://api.openai.com/v1/" @@ -65,6 +67,20 @@ func Completions(msg string) (string, error) { req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+apiKey) client := &http.Client{} + + httpProxy := config.LoadConfig().ProxyURL + if httpProxy != "" { + uri, err := url.Parse(httpProxy) + if err != nil { + return "", err + } + client = &http.Client{ + Transport: &http.Transport{ + Proxy: http.ProxyURL(uri), + }, + } + } + response, err := client.Do(req) if err != nil { return "", err