From 8c672f7186867cf9a6f9132d9c6c2b4775f0b6b7 Mon Sep 17 00:00:00 2001 From: Giovanni Harting <539@idlegandalf.com> Date: Sat, 12 Feb 2022 01:59:32 +0100 Subject: [PATCH] added timout to deepl post request --- config_example.yaml | 11 +++++++---- main.go | 2 +- utils/utils.go | 17 +++++++++++------ 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/config_example.yaml b/config_example.yaml index 3a46832..abf832b 100644 --- a/config_example.yaml +++ b/config_example.yaml @@ -51,7 +51,10 @@ csgowtfd: write: 30 # seconds before closing idle connections idle: 120 - deepl: - base_url: api-free.deepl.com - # get your API key on deepl.com - api_key: \ No newline at end of file + +deepl: + base_url: api-free.deepl.com + # get your API key on deepl.com + api_key: + # timeout in sec to wait for deepl response + timeout: 15 \ No newline at end of file diff --git a/main.go b/main.go index aa734a1..136ef88 100644 --- a/main.go +++ b/main.go @@ -702,7 +702,7 @@ func getMatchChat(w http.ResponseWriter, r *http.Request) { if translate { lang, _ := tag[0].Base() translated, srcLang, err := utils.TranslateWithDeepL(stat.Message, lang.String(), - conf.Csgowtfd.DeepL.BaseURL, conf.Csgowtfd.DeepL.APIKey) + conf.DeepL.BaseURL, conf.DeepL.APIKey, conf.DeepL.Timeout) if err != nil { log.Warningf("[GMC] Unable to translate %s with DeepL: %v", stat.Message, err) goto sendNormalResp diff --git a/utils/utils.go b/utils/utils.go index 34f7049..4b2bf4d 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -70,11 +70,12 @@ type Conf struct { Write int Idle int } - DeepL struct { - BaseURL string `yaml:"base_url"` - APIKey string `yaml:"api_key"` - } `yaml:"deepl"` } + DeepL struct { + BaseURL string `yaml:"base_url"` + APIKey string `yaml:"api_key"` + Timeout int `yaml:"timeout"` + } `yaml:"deepl"` } type CommunityXML struct { @@ -687,18 +688,22 @@ func PlayerFromSteamID64(db *ent.Client, steamID uint64, apiKey string, rl ratel } } -func TranslateWithDeepL(text string, language string, baseURL string, apiKey string) (translated string, detectedLanguage string, err error) { +func TranslateWithDeepL(text string, language string, baseURL string, apiKey string, timeout int) (translated string, detectedLanguage string, err error) { + c := &http.Client{ + Timeout: time.Duration(timeout) * time.Second, + } v := url.Values{} v.Set("auth_key", apiKey) v.Set("text", text) v.Set("target_lang", language) - dlResp, err := http.PostForm("https://"+baseURL+"/v2/translate", v) + dlResp, err := c.PostForm("https://"+baseURL+"/v2/translate", v) if err != nil { return "", "", fmt.Errorf("deepl response: %w", err) } else if dlResp.StatusCode != http.StatusOK { return "", "", fmt.Errorf("deepl response %d", dlResp.StatusCode) } else { respBytes, err := io.ReadAll(dlResp.Body) + defer dlResp.Body.Close() if err != nil { return "", "", fmt.Errorf("error reading deepl response: %w", err) }