summaryrefslogtreecommitdiffhomepage
path: root/main.go
blob: ba475fd48ba231aace20d21d4fa5c28cbc5ffaaf (plain) (blame)
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
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"math"
	"net/http"
	"strconv"
	"strings"

	"git.thomasvoss.com/euro-cash.eu/i18n"
	"git.thomasvoss.com/euro-cash.eu/middleware"
	"git.thomasvoss.com/euro-cash.eu/templates"
	"github.com/a-h/templ"
)

var components = map[string]templ.Component{
	"/":         templates.Index(),
	"/language": templates.SetLanguage(),
}

func main() {
	i18n.InitPrinters()

	port := flag.Int("port", 8080, "port number")
	flag.Parse()

	fs := http.FileServer(http.Dir("static"))
	mux := http.NewServeMux()
	mux.Handle("GET /favicon.ico", fs)
	mux.Handle("GET /style.css", fs)
	mux.Handle("GET /", middleware.I18n(http.HandlerFunc(finalHandler)))
	mux.Handle("POST /language", http.HandlerFunc(setUserLanguage))

	portStr := ":" + strconv.Itoa(*port)
	log.Println("Listening on", portStr)
	log.Fatal(http.ListenAndServe(portStr, mux))
}

func finalHandler(w http.ResponseWriter, r *http.Request) {
	p := r.Context().Value(middleware.PrinterKey).(i18n.Printer)

	/* Strip trailing slash from the URL */
	path := r.URL.Path
	if path != "/" && path[len(path)-1] == '/' {
		path = path[:len(path)-1]
	}

	if c, ok := components[path]; !ok {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintln(w, p.T("Page not found"))
	} else {
		templates.Root(nil, c).Render(r.Context(), w)
	}
}

func setUserLanguage(w http.ResponseWriter, r *http.Request) {
	loc := r.FormValue(templates.LocaleKey)
	_, ok := i18n.Printers[strings.ToLower(loc)]
	if !ok {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "Locale ā€˜%sā€™ is invalid or unsupported", loc)
		return
	}
	http.SetCookie(w, &http.Cookie{
		Name:   "lang",
		Value:  loc,
		MaxAge: math.MaxInt32,
	})
}