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" ) // flags var ( port uint64 host string ) 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() 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()) 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, "content", u.Name) } }