Add --proxy option

This commit is contained in:
Alexey Yerin 2021-01-18 23:02:00 +03:00
parent 1a32c713bc
commit 7a297bb0d8
2 changed files with 30 additions and 4 deletions

17
main.go
View File

@ -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)
}

View File

@ -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)
}