Add --user-agent option
This commit is contained in:
parent
7a297bb0d8
commit
fc80e5334b
|
@ -34,5 +34,4 @@ templates and static directories:
|
|||
|
||||
# TODO
|
||||
- Proper language selector
|
||||
- Change `User-Agent`
|
||||
- Dark theme
|
||||
|
|
5
main.go
5
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)
|
||||
}
|
||||
|
|
14
translate.go
14
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)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue