summaryrefslogtreecommitdiff
path: root/main.go
blob: 29564ffccde1ee3c9528c0615a524ed4d18c8be8 (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
package main

import (
	"context"
	"embed"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"xengineering.eu/ceres/controller"
	"xengineering.eu/ceres/model"
	"xengineering.eu/ceres/view"

	"github.com/gorilla/mux"
)

func main() {
	model.InitStorage()
	defer model.RemoveStorage()

	model.InitDatabase()
	defer model.CloseDatabase()

	view.Init()

	var srv *http.Server = startServer("127.0.0.1:8080")
	go srv.ListenAndServe()
	defer stopServer(srv)

	listener := make(chan os.Signal)
	signal.Notify(listener, syscall.SIGTERM)
	signal.Notify(listener, syscall.SIGINT)
	sig := <-listener
	log.Printf("Cleaning up due to OS signal '%v'\n", sig)
}

//go:embed view/static/simple.css/simple.css
var static embed.FS

func startServer(addr string) *http.Server {
	var r *mux.Router = mux.NewRouter()

	r.PathPrefix("/static/").
		Handler(http.StripPrefix("/static/", http.FileServer(http.FS(static))))

	r.HandleFunc("/recipes/{id}", view.HandlerHTML(&model.Recipe{})).Methods(`GET`)
	r.HandleFunc("/recipes/{id}/edit", view.RecipeEditHandler).Methods(`GET`)
	r.HandleFunc("/recipes/{id}", controller.RecipePost).Methods(`POST`)

	r.HandleFunc("/recipes/{id}/steps/{step_id}",
	             view.HandlerHTML(&model.RecipeStep{})).Methods(`GET`)

	r.HandleFunc("/", view.HandlerHTML(&model.Index{})).Methods(`GET`)

	muxer := http.NewServeMux()
	muxer.Handle("/", r)

	var srv http.Server
	srv.Addr = addr
	srv.Handler = muxer

	log.Printf("Configured server to listen on http://%s\n", srv.Addr)

	return &srv
}

func stopServer(srv *http.Server) {
	var err error = srv.Shutdown(context.Background())
	if err != nil {
		log.Printf("Failed to shutdown HTTP server: %v\n", err)
	} else {
		log.Println("Stopped HTTP server")
	}
}