summaryrefslogtreecommitdiff
path: root/main.go
blob: 38bfd93c8dab5dda715b62a271c9e7930516c77d (plain)
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
package main

import (
	"flag"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"

	"github.com/gorilla/handlers"

	"gosten/model"
	"gosten/templ"
)

// flags
var (
	port uint64
	host string
)

func init() {
	flag.StringVar(&host, "h", "localhost", "address to listen on")
	flag.Uint64Var(&port, "p", 8080, "port to listen on")
}

var Q *model.Queries

func main() {
	flag.Parse()

	db := openDB("")
	if err := db.Ping(); err != nil {
		log.Fatal(err)
	}

	Q = model.New(db)

	mux := http.NewServeMux()

	mux.Handle("GET /login", loginPage())
	mux.HandleFunc("POST /login", handleLogin)
	mux.Handle("GET /logout", handleLogout())
	mux.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("static"))))
	mux.Handle("/favicon.ico", http.NotFoundHandler())

	handler := sessionHandler(csrfHandler(mux))
	handler = handlers.CombinedLoggingHandler(os.Stderr, handler)
	handler = handlers.ProxyHeaders(handler)

	// the real content, needing authentification
	authMux := http.NewServeMux()
	mux.Handle("/", RequireAuth(authMux))

	authMux.Handle("GET /{$}", indexPage())

	address := net.JoinHostPort(host, strconv.FormatUint(port, 10))
	log.Fatal(http.ListenAndServe(address, handler))
}

func showTemplate(w http.ResponseWriter, tpl string, data any) {
	if err := templ.Lookup(tpl).Execute(w, data); err != nil {
		log.Panicf("Executing '%s' with %+v: %v", tpl, data, err)
	}
}

func indexPage() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		uid := userId(r)
		u, _ := Q.GetUserById(r.Context(), uid)
		showTemplate(w, "index", u.Name)
	}
}