aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: 9231f7c8b25ef177d27774f76e0591d98dc6685d (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main

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

	"fagott.pw/charakterin"
	"fagott.pw/grilist/frontend"
	"fagott.pw/grilist/grilist"
	"fagott.pw/grilist/modules/grils"
	"fagott.pw/grilist/modules/lists"
	"fagott.pw/grilist/modules/search"
	"fagott.pw/grilist/modules/tags"
	"fagott.pw/grilist/modules/user"

	"strings"

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

var app *grilist.Grilist

func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	if strings.Index(r.Referer(), "127.0.0.1") != -1 {
		w.WriteHeader(200)
		return
	}
	http.Redirect(w, r, "/dashboard", 301)
}

func loadModule(mod grilist.Module) error {
	if _, ok := app.Modules[mod.Name()]; ok {
		return fmt.Errorf("module with name %s already exists", mod.Name())
	}
	app.Modules[mod.Name()] = mod
	mod.Init(app)
	return nil
}

func main() {
	config := grilist.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")
	login := charakterin.New(db)
	login.UseRenderer(renderer)

	router := httprouter.New()

	app = &grilist.Grilist{
		config,
		renderer,
		login,
		db,
		make(map[string]grilist.Module),
		router,
	}

	router.GET("/", index)
	router.GET("/health", app.HealthCheck)
	router.HandlerFunc("GET", "/login", login.DisplayLogin)
	router.HandlerFunc("POST", "/login", login.Login)
	router.HandlerFunc("GET", "/settings", login.DisplayUserSettings)
	router.HandlerFunc("POST", "/settings", login.SaveUserRoute)
	router.HandlerFunc("GET", "/logout", login.Logout)
	router.HandlerFunc("GET", "/register", login.DisplayRegistration)
	router.HandlerFunc("POST", "/register", login.Register)

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

	// Module laden
	loadModule(grils.New())
	loadModule(lists.New())
	loadModule(tags.New())
	loadModule(search.New())
	loadModule(user.New())
	router.GET("/dashboard", viewDashboard)

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