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