This repository has been archived by the owner on Mar 30, 2022. It is now read-only.
forked from buidl-labs/churrofi-reminder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
95 lines (77 loc) · 1.86 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"context"
"log"
"os"
"reminders/database"
"reminders/handlers"
"reminders/mail"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"github.com/joho/godotenv"
"github.com/robfig/cron"
)
func main() {
if err := godotenv.Load(); err != nil {
log.Fatal(err)
}
DB_URL := os.Getenv("DB_URL")
log.Println(DB_URL)
if DB_URL == "" {
log.Fatal("Please provide a DB url.")
}
DB := database.New(DB_URL)
defer DB.Close()
// DB.AddQueryHook(pgdebug.DebugHook{
// Verbose: true,
// })
ctx := context.Background()
if err := DB.Ping(ctx); err != nil {
log.Println(err)
}
// dropTable(DB)
createTable(DB, false)
// SCHEDULER TO PERIODICALLY SEND EMAILS
scheduler := cron.New()
scheduler.AddFunc("@every 2h", func() {
MAIL_DOMAIN := os.Getenv("MAILGUN_DOMAIN")
MAIL_APIKEY := os.Getenv("MAILGUN_API_KEY")
log.Println("Fetching reminders to send")
remindersToSend, err := database.GetRemindersToSend(DB)
if err != nil {
log.Fatal("Can't fetch reminders from DB")
}
log.Println("Amount of reminders to send", len(remindersToSend))
for _, reminder := range remindersToSend {
if _, err = mail.SendReminder(*reminder, MAIL_DOMAIN, MAIL_APIKEY); err == nil {
log.Println(database.MarkReminderDone(DB, reminder))
}
}
})
scheduler.Start()
r := gin.Default()
// CORS middleware
r.Use(cors.Default())
// Routes
r.GET("/", handlers.IndexGet())
r.GET("/reminder", handlers.ReminderGet(DB))
r.POST("/reminder", handlers.ReminderPost(DB))
// Running the app
r.Run()
}
func dropTable(DB *pg.DB) {
_, err := DB.Exec("drop table reminders")
if err != nil {
panic(err)
}
}
func createTable(DB *pg.DB, temp bool) {
err := DB.Model((*database.Reminder)(nil)).CreateTable(&orm.CreateTableOptions{
Temp: temp,
})
if err != nil {
log.Print(err)
}
}