Move request logic to a different function
This commit is contained in:
parent
ef9c46bdbe
commit
202aca33bb
26
translate.go
26
translate.go
|
@ -10,15 +10,7 @@ import (
|
||||||
"golang.org/x/net/html"
|
"golang.org/x/net/html"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Requests and parses translation from Google
|
func doRequest(settings *TranslateSettings, reqUrl string) (*http.Response, error) {
|
||||||
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)
|
|
||||||
|
|
||||||
client := &http.Client{}
|
client := &http.Client{}
|
||||||
|
|
||||||
if settings.proxy != nil {
|
if settings.proxy != nil {
|
||||||
|
@ -28,12 +20,26 @@ func Translate(settings *TranslateSettings, fromLang, toLang, text string) (stri
|
||||||
|
|
||||||
req, err := http.NewRequest("GET", reqUrl, nil)
|
req, err := http.NewRequest("GET", reqUrl, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Header["User-Agent"] = []string{settings.userAgent}
|
req.Header["User-Agent"] = []string{settings.userAgent}
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
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 {
|
if err != nil {
|
||||||
return "", fmt.Errorf("Request failed: %v", err)
|
return "", fmt.Errorf("Request failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue