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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
package main
import (
"context"
"log"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/joho/godotenv"
"gosten/model"
"gosten/templ"
)
var Q *model.Queries
func checkEnvEntry(e string) {
if os.Getenv(e) == "" {
log.Fatalf("Variable '%s' not set", e)
}
}
func checkEnv() {
checkEnvEntry("GOSTEN_DSN")
checkEnvEntry("GOSTEN_ADDRESS")
}
func main() {
if err := godotenv.Load(); err != nil {
log.Fatal("Loading env file: ", err)
}
checkEnv()
db, err := pgxpool.New(context.Background(), os.Getenv("GOSTEN_DSN"))
if err != nil {
log.Fatal(err)
}
if err := db.Ping(context.Background()); err != nil {
log.Fatal(err)
}
defer db.Close()
Q = model.New(db)
mux := http.NewServeMux()
// handlers that DO NOT require authentification
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)
// setup authentification
authMux := http.NewServeMux()
mux.Handle("/", RequireAuth(authMux))
// handlers that required authentification
authMux.Handle("GET /{$}", indexPage())
authMux.Handle("GET /", notfound())
log.Fatal(http.ListenAndServe(os.Getenv("GOSTEN_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)
}
}
func notfound() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
showTemplate(w, "404", r.RequestURI)
}
}
|