From fc80e5334b147ef940b1ec21d9c625f7f26e0bca Mon Sep 17 00:00:00 2001 From: Alexey Yerin Date: Mon, 18 Jan 2021 23:08:57 +0300 Subject: [PATCH] Add --user-agent option --- README.md | 1 - main.go | 5 +++-- translate.go | 14 ++++++++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 510b905..8fb5b55 100644 --- a/README.md +++ b/README.md @@ -34,5 +34,4 @@ templates and static directories: # TODO - Proper language selector -- Change `User-Agent` - Dark theme diff --git a/main.go b/main.go index 810cfd0..a64f068 100644 --- a/main.go +++ b/main.go @@ -33,6 +33,7 @@ func main() { templateDir := pflag.String("template-dir", "./templates", "Templates directory") staticDir := pflag.String("static-dir", "./static", "Static files directory") proxy := pflag.String("proxy", "", "Proxy URL, with no scheme http is assumed") + userAgent := pflag.String("user-agent", "", "User-Agent header to use") pflag.Parse() var proxyUrl *url.URL @@ -60,7 +61,7 @@ func main() { to := req.FormValue("to") text := req.FormValue("text") - translation, err := Translate(from, to, text, proxyUrl) + translation, err := Translate(from, to, text, *userAgent, proxyUrl) if err != nil { writeError(w, 500, err) } @@ -92,7 +93,7 @@ func main() { return } - translation, err := Translate(from, to, text, proxyUrl) + translation, err := Translate(from, to, text, *userAgent, proxyUrl) if err != nil { writeError(w, 500, err) } diff --git a/translate.go b/translate.go index 1f136e1..f3b35cd 100644 --- a/translate.go +++ b/translate.go @@ -10,7 +10,7 @@ import ( "golang.org/x/net/html" ) -func getWithProxy(url string, proxy *url.URL) (*http.Response, error) { +func getWithProxy(url string, userAgent string, proxy *url.URL) (*http.Response, error) { client := &http.Client{} if proxy != nil { @@ -18,13 +18,19 @@ func getWithProxy(url string, proxy *url.URL) (*http.Response, error) { client.Transport = tr } - resp, err := client.Get(url) + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, err + } + req.Header["User-Agent"] = []string{userAgent} + + resp, err := client.Do(req) return resp, err } // Requests and parses translation from Google -func Translate(fromLang, toLang, text string, proxy *url.URL) (string, error) { +func Translate(fromLang, toLang, text string, userAgent string, proxy *url.URL) (string, error) { // Escape parameters before embedding in URL fromLang = url.QueryEscape(fromLang) toLang = url.QueryEscape(toLang) @@ -32,7 +38,7 @@ func Translate(fromLang, toLang, text string, proxy *url.URL) (string, error) { url := fmt.Sprintf("https://translate.google.com/m?sl=%s&tl=%s&q=%s", fromLang, toLang, text) - resp, err := getWithProxy(url, proxy) + resp, err := getWithProxy(url, userAgent, proxy) if err != nil { return "", fmt.Errorf("Request failed: %v", err) }