~yerinalexey/gtranslate

ref: bf49f944269ced7848aecf7372962a981f29785a gtranslate/main.go -rw-r--r-- 2.1 KiB
bf49f944 — Kyle Anthony Williams Use <select> for language selection 8 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// gtranslate - Better front-end for Google Translate
// Copyright (C) 2021-present Alexey Yerin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package main

import (
	"html/template"
	"log"
	"net/http"
	"net/url"
	"path"
	"strings"

	"github.com/gorilla/mux"
	"github.com/spf13/pflag"
)

type TranslateSettings struct {
	proxy     *url.URL
	userAgent string
}

func main() {
	bind := pflag.StringP("bind", "b", ":5000", "Address to bind the server to, [addr]:port")
	templatesDir := pflag.String("templates-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
	if *proxy != "" {
		u, err := url.Parse(*proxy)

		if err != nil {
			log.Fatalln("Invalid proxy URL:", err)
		}

		proxyUrl = u
	}

	settings := TranslateSettings{proxyUrl, *userAgent}

	funcMap := template.FuncMap{
		"title": strings.Title,
	}

	tmpl := template.Must(template.New("index").Funcs(funcMap).ParseGlob(path.Join(*templatesDir, "*.html")))

	r := mux.NewRouter()

	r.HandleFunc("/", CreateWebHandler(tmpl, &settings)).Methods("GET", "POST")
	r.HandleFunc("/api", CreateApiHandler(&settings)).Methods("POST")

	// Static files
	fs := http.FileServer(http.Dir(*staticDir))
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

	log.Println("Starting on", *bind)
	log.Fatalln(http.ListenAndServe(*bind, r))
}