~yerinalexey/gtranslate

ref: c792f7f5703265db6075505dea0d3975e095be3c gtranslate/web.go -rw-r--r-- 1007 bytes
c792f7f5Alexey Yerin web: reject any whitespace-only input 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
	"html/template"
	"net/http"
	"strings"
)

func CreateWebHandler(tmpl *template.Template, settings *TranslateSettings) func(w http.ResponseWriter, req *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		type indexPageData struct {
			Languages   map[string]string
			From        string
			To          string
			Text        string
			Translation string
		}

		if req.Method == "GET" {
			tmpl.ExecuteTemplate(w, "index", indexPageData{Languages, "auto", "en", "", ""})
			return
		}

		from := req.FormValue("from")
		to := req.FormValue("to")
		text := req.FormValue("text")

		if strings.TrimSpace(text) == "" {
			tmpl.ExecuteTemplate(w, "index", indexPageData{Languages, from, to, text, ""})
			return
		}

		translation, err := Translate(settings, from, to, text)
		if err != nil {
			w.WriteHeader(500)
			tmpl.ExecuteTemplate(w, "error", err);
			return
		}

		tmpl.ExecuteTemplate(w, "index", indexPageData{Languages, from, to, text, translation})
	}
}