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,15 +10,7 @@ import (
"golang.org/x/net/html"
)
// Requests and parses translation from Google
func Translate(settings *TranslateSettings, fromLang, toLang, text string) (string, error) {
// Escape parameters before embedding in URL
fromLang = url.QueryEscape(fromLang)
toLang = url.QueryEscape(toLang)
text = url.QueryEscape(text)
reqUrl := fmt.Sprintf("https://translate.google.com/m?sl=%s&tl=%s&q=%s", fromLang, toLang, text)
func doRequest(settings *TranslateSettings, reqUrl string) (*http.Response, error) {
client := &http.Client{}
if settings.proxy != nil {
@ -28,12 +20,26 @@ func Translate(settings *TranslateSettings, fromLang, toLang, text string) (stri
req, err := http.NewRequest("GET", reqUrl, nil)
if err != nil {
return "", err
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
fromLang = url.QueryEscape(fromLang)
toLang = url.QueryEscape(toLang)
text = url.QueryEscape(text)
reqUrl := fmt.Sprintf("https://translate.google.com/m?sl=%s&tl=%s&q=%s", fromLang, toLang, text)
resp, err := doRequest(settings, reqUrl)
if err != nil {
return "", fmt.Errorf("Request failed: %v", err)
}