gtranslate/web.go

43 lines
1006 B
Go
Raw Normal View History

2021-01-22 20:42:13 +00:00
package main
import (
"html/template"
"net/http"
2021-05-11 08:32:38 +00:00
"strings"
2021-01-22 20:42:13 +00:00
)
func CreateWebHandler(tmpl *template.Template, settings *TranslateSettings) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
2021-02-04 14:05:43 +00:00
type indexPageData struct {
Languages map[string]string
From string
To string
Text string
Translation string
}
2021-01-22 20:42:13 +00:00
if req.Method == "GET" {
tmpl.ExecuteTemplate(w, "index", indexPageData{Languages, "auto", "en", "", ""})
2021-01-22 20:42:13 +00:00
return
}
from := req.FormValue("from")
to := req.FormValue("to")
text := req.FormValue("text")
2021-05-11 08:32:38 +00:00
if strings.TrimSpace(text) == "" {
tmpl.ExecuteTemplate(w, "index", indexPageData{Languages, from, to, text, ""})
return
}
2021-01-22 20:42:13 +00:00
translation, err := Translate(settings, from, to, text)
if err != nil {
2021-05-10 17:09:50 +00:00
w.WriteHeader(500)
2021-05-11 08:33:29 +00:00
tmpl.ExecuteTemplate(w, "error", err)
return
2021-01-22 20:42:13 +00:00
}
2021-02-04 14:05:43 +00:00
tmpl.ExecuteTemplate(w, "index", indexPageData{Languages, from, to, text, translation})
2021-01-22 20:42:13 +00:00
}
}