aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: f367922136deaa4b5794e7fde10e68b2e4625edf (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
package main

import (
	"database/sql"
	"log"
	"net/http"

	login "fagott.pw/charakterin"
	"fagott.pw/grilist/frontend"

	"github.com/julienschmidt/httprouter"
	_ "github.com/lib/pq"
)

var renderer *frontend.Renderer
var charakterin *login.Charakterin

func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	user, err := charakterin.GetUserFromRequest(r)
	if err != nil {
		http.Redirect(w, r, "/login", 302)
		return
	}

	data := make(map[string]interface{})

	data["username"] = user.GetName()
	renderer.RenderPage("index", w, data)
}

func main() {
	config := LoadConfig()
	db, err := sql.Open("postgres", config.DBConnectionString())
	if err != nil {
		log.Fatal(err)
	}
	if err := db.Ping(); err != nil {
		log.Fatal(err)
	}

	log.Println("database connection established")

	renderer = frontend.New("views")
	charakterin = login.New(db)
	charakterin.UseRenderer(renderer)

	router := httprouter.New()
	router.HandlerFunc("GET", "/login", charakterin.DisplayLogin)
	router.HandlerFunc("POST", "/login", charakterin.Login)
	router.HandlerFunc("GET", "/logout", charakterin.Logout)
	router.HandlerFunc("GET", "/register", charakterin.DisplayRegistration)
	router.HandlerFunc("POST", "/register", charakterin.Register)
	router.GET("/", index)

	fs := http.FileServer(http.Dir("assets"))
	http.Handle("/assets/", http.StripPrefix("/assets/", fs))

	http.Handle("/", router)

	log.Fatal(http.ListenAndServe(":8080", nil))
}