-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
94 lines (79 loc) · 2.17 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
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/joho/godotenv"
"github.com/webstradev/rsdb-backend/auth"
"github.com/webstradev/rsdb-backend/db"
"github.com/webstradev/rsdb-backend/migrations"
"github.com/webstradev/rsdb-backend/utils"
)
func main() {
// Load environment variables
loadEnvironmentVariables()
// Set up database instance
db, err := db.Setup(os.Getenv("DB_CONNECTION_STRING"), migrations.LoadMigrations())
if err != nil {
log.Fatal(err)
}
// Test database connection
db.Ping()
// Migrate Database
err = db.Migrate()
if err != nil {
log.Fatal(err)
}
jwtService, err := auth.CreateJWTService(os.Getenv("JWT_SIGNING_SECRET"), os.Getenv("JWT_ISSUER"), 24*time.Hour)
if err != nil {
log.Fatal(err)
}
// Initialize Environment (for dependency injection)
env := &utils.Environment{
DB: db,
JWT: jwtService,
UUID: auth.NewUUIDService(),
AuthService: auth.NewAuthService(),
}
// Server object
s := &http.Server{
Addr: ":8080",
Handler: registerRoutes(env),
IdleTimeout: 120 * time.Second,
ReadTimeout: 2 * time.Second,
WriteTimeout: 2 * time.Second,
}
// Initializing the server in a goroutine so that
// it won't block the graceful shutdown handling below
go func() {
if err := s.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
log.Println("Failed to listen and serve")
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil {
log.Fatalln("Server forced to shutdown")
}
log.Println("Server exiting.")
}
func loadEnvironmentVariables() {
// If a database connection string is not yet set in environment variables (or by kube secrets) then load the .env file
if os.Getenv("DB_CONNECTION_STRING") == "" {
err := godotenv.Load(".env")
if err != nil {
log.Fatal(err)
}
}
}