main.go (view raw)
1package main
2
3import (
4 "fmt"
5 "log"
6 "net/http"
7 "os"
8 "path"
9 "strconv"
10 "time"
11
12 "github.com/joho/godotenv"
13 "gorm.io/driver/sqlite"
14 "gorm.io/gorm"
15)
16
17// Occurrence represents a scheduled event
18type Occurrence struct {
19 ID uint `json:"id" gorm:"primaryKey"`
20 CreatedAt time.Time `json:"created_at"`
21 UpdatedAt time.Time `json:"updated_at"`
22
23 Day uint `json:"day"`
24 Month uint `json:"month"`
25 Year *uint `json:"year"`
26 Name string `json:"name"`
27 Description string `json:"description"`
28 Notify bool `json:"notify"`
29 Notified bool `json:"notified"`
30 NotifiedSoft bool `json:"notified_soft"`
31}
32
33const (
34 dataDir = "data"
35 dbFile = "occurrences.db"
36 defaultNotificationWindow = 3
37 defaultSleepDuration = 1
38 defaultPort = "3000"
39)
40
41var (
42 db *gorm.DB
43 port string
44)
45
46func initDB() {
47 if _, err := os.Stat(dataDir); os.IsNotExist(err) {
48 err := os.Mkdir(dataDir, os.ModePerm)
49 if err != nil {
50 log.Fatal("Failed to create directory:", err)
51 }
52 }
53
54 var err error
55 db, err = gorm.Open(sqlite.Open(path.Join(dataDir, dbFile)), &gorm.Config{})
56 if err != nil {
57 log.Fatal("Failed to connect to database:", err)
58 }
59
60 db.AutoMigrate(&Occurrence{})
61}
62
63func loadEnv() {
64 err := godotenv.Load()
65 if err != nil {
66 log.Println("Error loading .env file")
67 }
68
69 NotificationWindow, err = strconv.Atoi(os.Getenv("DAYS_BEFORE_NOTIFICATION"))
70 if err != nil {
71 NotificationWindow = defaultNotificationWindow
72 }
73 log.Println("Notification window (days):", NotificationWindow)
74
75 loadedSleepDuration, err := strconv.Atoi(os.Getenv("HOURS_BETWEEN_CHECKS"))
76 if err != nil {
77 SleepDuration = defaultSleepDuration * time.Hour
78 } else {
79 SleepDuration = time.Duration(loadedSleepDuration) * time.Hour
80 }
81 log.Println("Sleep duration:", SleepDuration)
82
83 port = os.Getenv("PORT")
84 if port == "" {
85 port = defaultPort
86 }
87}
88
89func main() {
90 loadEnv()
91 initDB()
92 ParseTemplates()
93
94 go CheckOccurrences()
95
96 http.HandleFunc("GET /", ShowIndexPage)
97
98 http.HandleFunc("GET /occurrences", getOccurrences)
99 http.HandleFunc("POST /occurrences", addOccurrence)
100 http.HandleFunc("DELETE /occurrences/{id}", deleteOccurrence)
101
102 log.Println("Starting server at port " + port + "...")
103 if err := http.ListenAndServe(":"+port, nil); err != nil {
104 fmt.Println("Server failed to start:", err)
105 }
106}