From 2b3189364ab8a6d27bb1f20a1ea1de34855d49ac Mon Sep 17 00:00:00 2001 From: Frank Elsinga Date: Thu, 14 Sep 2023 01:07:47 +0200 Subject: [PATCH] extracted the db-intalisation to a separate function --- server/main.go | 44 +++++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/server/main.go b/server/main.go index 10d18e0e..30cde9e3 100644 --- a/server/main.go +++ b/server/main.go @@ -55,25 +55,7 @@ func main() { log.WithError(err).Error("InfluxDB connection failed - health check failed") } - // Connect to DB - var conn gorm.Dialector - if dbHost := os.Getenv("DB_DSN"); dbHost == "" { - log.Fatal("Failed to start! The 'DB_DSN' environment variable is not defined. Take a look at the README.md for more details.") - } else { - log.Info("Connecting to dsn") - conn = mysql.Open(dbHost) - } - - db, err := gorm.Open(conn, &gorm.Config{}) - if err != nil { - log.WithError(err).Panic("failed to connect database") - } - - // Migrate the schema - // currently not activated as - if err := migration.New(db, false).Migrate(); err != nil { - log.WithError(err).Fatal("Failed to migrate database") - } + db := setupDB() // Create any other background services (these shouldn't do any long-running work here) cronService := cron.New(db) @@ -142,6 +124,30 @@ func main() { } } +// setupDB connects to the database and migrates it if necessary +func setupDB() *gorm.DB { + // Connect to DB + var conn gorm.Dialector + if dbHost := os.Getenv("DB_DSN"); dbHost == "" { + log.Fatal("Failed to start! The 'DB_DSN' environment variable is not defined. Take a look at the README.md for more details.") + } else { + log.Info("Connecting to dsn") + conn = mysql.Open(dbHost) + } + + db, err := gorm.Open(conn, &gorm.Config{}) + if err != nil { + log.WithError(err).Panic("failed to connect database") + } + + // Migrate the schema + // currently not activated as + if err := migration.New(db, false).Migrate(); err != nil { + log.WithError(err).Fatal("Failed to migrate database") + } + return db +} + // setupTelemetry initializes our telemetry stack // - sentry to be connected with log // - logrus to