-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
73 lines (60 loc) · 1.68 KB
/
main.go
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
package main
import (
"errors"
"fmt"
"html/template"
"log"
"net/http"
"os"
"strconv"
"github.com/saaste/memento-mori/calendar"
"github.com/saaste/memento-mori/config"
"github.com/saaste/memento-mori/utils"
)
type IndexData struct {
Birthday utils.Date
LifeExpectancy int
Years []calendar.Year
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
config, err := config.ReadConfig()
if err != nil {
log.Fatalf("ERROR: reading config.json failed: %s\n", err)
}
years := calendar.GetYears(config.Birthday.Year(), config.LifeExpectancy, config)
tmpl := template.Must(template.ParseFiles("./templates/index.html"))
data := IndexData{
Birthday: config.Birthday,
LifeExpectancy: config.LifeExpectancy,
Years: years,
}
tmpl.Execute(w, data)
}
func main() {
if !utils.FileExists("./config.json") {
log.Fatalln("ERROR: config.json does not exist")
}
if !utils.FileExists("./static/labels.css") {
log.Fatalln("ERROR: static/labels.css does not exist")
}
port := "3333"
args := os.Args[1:]
if len(args) > 0 {
if _, err := strconv.Atoi(args[0]); err != nil {
log.Fatalln("ERROR: port must be an integer")
}
port = args[0]
}
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot)
fs := http.FileServer(http.Dir("./static"))
mux.Handle("/static/", http.StripPrefix("/static/", fs))
fmt.Printf("Server running on port %s\n", port)
fmt.Printf("Go to http://localhost:%s to access your calendar\n", port)
err := http.ListenAndServe(fmt.Sprintf(":%s", port), mux)
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("Server closed\n")
} else if err != nil {
log.Fatalf("ERROR: unable to start the server: %s\n", err)
}
}