Move request logic to a different function

This commit is contained in:
Alexey Yerin 2021-01-18 23:25:21 +03:00
parent ef9c46bdbe
commit 202aca33bb
1 changed files with 21 additions and 15 deletions

View File

@ -10,6 +10,26 @@ import (
"golang.org/x/net/html"
)
func doRequest(settings *TranslateSettings, reqUrl string) (*http.Response, error) {
client := &http.Client{}
if settings.proxy != nil {
tr := &http.Transport{Proxy: http.ProxyURL(settings.proxy)}
client.Transport = tr
}
req, err := http.NewRequest("GET", reqUrl, nil)
if err != nil {
return nil, err
}
req.Header["User-Agent"] = []string{settings.userAgent}
resp, err := client.Do(req)
return resp, err
}
// Requests and parses translation from Google
func Translate(settings *TranslateSettings, fromLang, toLang, text string) (string, error) {
// Escape parameters before embedding in URL
@ -19,21 +39,7 @@ func Translate(settings *TranslateSettings, fromLang, toLang, text string) (stri
reqUrl := fmt.Sprintf("https://translate.google.com/m?sl=%s&tl=%s&q=%s", fromLang, toLang, text)
client := &http.Client{}
if settings.proxy != nil {
tr := &http.Transport{ Proxy: http.ProxyURL(settings.proxy) }
client.Transport = tr
}
req, err := http.NewRequest("GET", reqUrl, nil)
if err != nil {
return "", err
}
req.Header["User-Agent"] = []string{settings.userAgent}
resp, err := client.Do(req)
resp, err := doRequest(settings, reqUrl)
if err != nil {
return "", fmt.Errorf("Request failed: %v", err)
}