From 9afda27ab4a11ea48b2ed70d6ac764bdb913df69 Mon Sep 17 00:00:00 2001 From: Joren Date: Sat, 6 Jul 2024 17:16:13 +0200 Subject: [PATCH] Actually add db connection --- go.mod | 1 + main.go | 54 +++++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/go.mod b/go.mod index b5f4657..77e66f2 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.22.4 require ( github.com/BurntSushi/toml v1.4.0 github.com/bwmarrin/discordgo v0.28.1 + github.com/lib/pq v1.10.9 ) require ( diff --git a/main.go b/main.go index 102b92f..1cea043 100644 --- a/main.go +++ b/main.go @@ -2,15 +2,23 @@ package main import ( "fmt" + "log" "os" "os/signal" "syscall" + "database/sql" + "github.com/BurntSushi/toml" "github.com/bwmarrin/discordgo" + _ "github.com/lib/pq" ) -var client *discordgo.Session +var ( + config Config + client *discordgo.Session + db *sql.DB +) type Config struct { Discord Discord `toml:"discord"` @@ -37,35 +45,63 @@ func loadConfig(filename string) (Config, error) { return config, err } -func init() { - config, err := loadConfig("config.toml") +func connectDb(config Config) { + var err error + + connectionString := fmt.Sprintf( + "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", + config.Database.Host, + config.Database.Port, + config.Database.Username, + config.Database.Password, + config.Database.Name, + ) + log.Println(connectionString) + + db, err := sql.Open("postgres", connectionString) if err != nil { - fmt.Println("Error occurred whilst trying to load config:", err) + log.Fatalf("Error connecting to the database: %v", err) + } + defer db.Close() + + err = db.Ping() + if err != nil { + log.Fatalf("Error pinging the database: %v", err) + } +} + +func init() { + var err error + config, err = loadConfig("config.toml") + if err != nil { + log.Println("Error occurred whilst trying to load config:", err) return } client, err = discordgo.New("Bot " + config.Discord.Token) if err != nil { - fmt.Println("Error initializing bot:", err) + log.Println("Error initializing bot:", err) return } + connectDb(config) + } func main() { if client == nil { - fmt.Println("Bot client is not initialized") + log.Println("Bot client is not initialized") return } client.AddHandler(func(client *discordgo.Session, r *discordgo.Ready) { - fmt.Println("Bot is online") + log.Println("Bot is online") }) err := client.Open() if err != nil { - fmt.Println("Error opening connection:", err) + log.Println("Error opening connection:", err) return } @@ -73,7 +109,7 @@ func main() { signal.Notify(stop, os.Interrupt, syscall.SIGTERM) <-stop - fmt.Println("Gracefully shutting down.") + log.Println("Gracefully shutting down.") client.Close() }