Move request logic to a different function

master
Alexey Yerin 2 years ago
parent ef9c46bdbe
commit 202aca33bb
  1. 28
      translate.go

@ -10,30 +10,36 @@ 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 {
tr := &http.Transport{ Proxy: http.ProxyURL(settings.proxy) }
tr := &http.Transport{Proxy: http.ProxyURL(settings.proxy)}
client.Transport = tr
}
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)
}

Loading…
Cancel
Save