From 7a297bb0d826c527aee59c4688e05ceb96c166b5 Mon Sep 17 00:00:00 2001 From: Alexey Yerin Date: Mon, 18 Jan 2021 23:02:00 +0300 Subject: [PATCH] Add --proxy option --- main.go | 17 +++++++++++++++-- translate.go | 17 +++++++++++++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index fb1f271..810cfd0 100644 --- a/main.go +++ b/main.go @@ -21,6 +21,7 @@ import ( "html/template" "log" "net/http" + "net/url" "path" "github.com/gorilla/mux" @@ -31,8 +32,20 @@ func main() { bind := pflag.StringP("bind", "b", ":5000", "Address to bind the server to, [addr]:port") 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") pflag.Parse() + var proxyUrl *url.URL + if *proxy != "" { + u, err := url.Parse(*proxy) + + if err != nil { + log.Fatalln("Invalid proxy URL:", err) + } + + proxyUrl = u + } + tmpl := template.Must(template.ParseGlob(path.Join(*templateDir, "*.html"))) r := mux.NewRouter() @@ -47,7 +60,7 @@ func main() { to := req.FormValue("to") text := req.FormValue("text") - translation, err := Translate(from, to, text) + translation, err := Translate(from, to, text, proxyUrl) if err != nil { writeError(w, 500, err) } @@ -79,7 +92,7 @@ func main() { return } - translation, err := Translate(from, to, text) + translation, err := Translate(from, to, text, proxyUrl) if err != nil { writeError(w, 500, err) } diff --git a/translate.go b/translate.go index 6e45885..1f136e1 100644 --- a/translate.go +++ b/translate.go @@ -10,8 +10,21 @@ import ( "golang.org/x/net/html" ) +func getWithProxy(url string, proxy *url.URL) (*http.Response, error) { + client := &http.Client{} + + if proxy != nil { + tr := &http.Transport{ Proxy: http.ProxyURL(proxy) } + client.Transport = tr + } + + resp, err := client.Get(url) + + return resp, err +} + // Requests and parses translation from Google -func Translate(fromLang, toLang, text string) (string, error) { +func Translate(fromLang, toLang, text string, proxy *url.URL) (string, error) { // Escape parameters before embedding in URL fromLang = url.QueryEscape(fromLang) toLang = url.QueryEscape(toLang) @@ -19,7 +32,7 @@ func Translate(fromLang, toLang, text string) (string, error) { url := fmt.Sprintf("https://translate.google.com/m?sl=%s&tl=%s&q=%s", fromLang, toLang, text) - resp, err := http.Get(url) + resp, err := getWithProxy(url, proxy) if err != nil { return "", fmt.Errorf("Request failed: %v", err) }