Refactor and modify db init

This commit is contained in:
Joren 2024-07-06 17:27:04 +02:00
parent 9afda27ab4
commit f24c836cbc
Signed by: Joren
GPG Key ID: 280E33DFBC0F1B55

35
main.go
View File

@ -1,13 +1,12 @@
package main package main
import ( import (
"database/sql"
"fmt" "fmt"
"log" "log"
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
"database/sql"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
@ -15,9 +14,9 @@ import (
) )
var ( var (
config Config config Config
client *discordgo.Session client *discordgo.Session
db *sql.DB db *sql.DB
) )
type Config struct { type Config struct {
@ -38,16 +37,13 @@ type Database struct {
Password string `toml:"password"` Password string `toml:"password"`
} }
func loadConfig(filename string) (Config, error) { func loadConfig(filename string) (Config, error) {
var config Config var config Config
_, err := toml.DecodeFile(filename, &config) _, err := toml.DecodeFile(filename, &config)
return config, err return config, err
} }
func connectDb(config Config) { func connectDb(config Config) (*sql.DB, error) {
var err error
connectionString := fmt.Sprintf( connectionString := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
config.Database.Host, config.Database.Host,
@ -60,14 +56,17 @@ func connectDb(config Config) {
db, err := sql.Open("postgres", connectionString) db, err := sql.Open("postgres", connectionString)
if err != nil { if err != nil {
log.Fatalf("Error connecting to the database: %v", err) return nil, fmt.Errorf("error connecting to the database: %v", err)
} }
defer db.Close()
err = db.Ping() err = db.Ping()
if err != nil { if err != nil {
log.Fatalf("Error pinging the database: %v", err) db.Close()
return nil, fmt.Errorf("error pinging the database: %v", err)
} }
log.Println("Successfully connected to the database.")
return db, nil
} }
func init() { func init() {
@ -84,9 +83,11 @@ func init() {
return return
} }
connectDb(config) db, err = connectDb(config)
if err != nil {
log.Println("Error initializing db connection:", err)
return
}
} }
func main() { func main() {
@ -111,5 +112,9 @@ func main() {
log.Println("Gracefully shutting down.") log.Println("Gracefully shutting down.")
client.Close() client.Close()
if db != nil {
db.Close()
}
} }