all repos — cameraman @ 85f22f5ab0e2fc67d5a8679d88a09ae77d68c246

main.go (view raw)

  1package main
  2
  3import (
  4	"fmt"
  5	"log"
  6	"os"
  7	"path"
  8	"strconv"
  9	"time"
 10
 11	"github.com/gin-gonic/gin"
 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      `gorm:"primaryKey" json:"id"`
 20	Month       int       `json:"month"`
 21	Day         int       `json:"day"`
 22	Name        string    `json:"name"`
 23	Description string    `json:"description"`
 24	Notify      bool      `json:"notify"`
 25	Notified    bool      `json:"notified"`
 26	CreatedAt   time.Time `json:"-"`
 27	UpdatedAt   time.Time `json:"-"`
 28}
 29
 30const (
 31	dataDir                   = "data"
 32	dbFile                    = "occurrences.db"
 33	defaultNotificationWindow = 3
 34	defaultSleepDuration      = 1
 35	defaultPort               = 3000
 36)
 37
 38var (
 39	db   *gorm.DB
 40	port int
 41)
 42
 43func initDB() {
 44	if _, err := os.Stat(dataDir); os.IsNotExist(err) {
 45		err := os.Mkdir(dataDir, os.ModePerm)
 46		if err != nil {
 47			log.Fatal("Failed to create directory:", err)
 48		}
 49	}
 50
 51	var err error
 52	db, err = gorm.Open(sqlite.Open(path.Join(dataDir, dbFile)), &gorm.Config{})
 53	if err != nil {
 54		log.Fatal("Failed to connect to database:", err)
 55	}
 56
 57	db.AutoMigrate(&Occurrence{})
 58}
 59
 60func loadEnv() {
 61	err := godotenv.Load()
 62	if err != nil {
 63		log.Println("Error loading .env file")
 64	}
 65
 66	NotificationWindow, err = strconv.Atoi(os.Getenv("DAYS_BEFORE_NOTIFICATION"))
 67	if err != nil {
 68		NotificationWindow = defaultNotificationWindow
 69	}
 70	log.Println("Notification window (days):", NotificationWindow)
 71
 72	loadedSleepDuration, err := strconv.Atoi(os.Getenv("HOURS_BETWEEN_CHECKS"))
 73	if err != nil {
 74		SleepDuration = defaultSleepDuration * time.Hour
 75	} else {
 76		SleepDuration = time.Duration(loadedSleepDuration) * time.Hour
 77	}
 78	log.Println("Sleep duration:", SleepDuration)
 79
 80	port, err = strconv.Atoi(os.Getenv("PORT"))
 81	if err != nil {
 82		port = defaultPort
 83	}
 84	log.Println("Port:", port)
 85}
 86
 87func main() {
 88	loadEnv()
 89	initDB()
 90	ParseTemplates()
 91
 92	go CheckOccurrences()
 93
 94	router := gin.Default()
 95	router.POST("/occurrences", addOccurrence)
 96	router.GET("/occurrences", getOccurrences)
 97	router.DELETE("/occurrences/:id", deleteOccurrence)
 98	router.GET("/", ShowIndexPage)
 99
100	router.Run(fmt.Sprintf(":%d", port))
101}