ekzyis 7558655458 refactor: Structure code into different packages
I have put too much code into the same files.

Also, I put everything into the same package: main.

This package is only meant for executables.

Therefore, I have refactored my code to use multiple packages. These packages also guarantee separation of concerns since Golang doesn't allow cyclic imports.
2023-09-10 23:13:08 +02:00

46 lines
689 B
Go

package db
import (
"database/sql"
"log"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"github.com/namsral/flag"
)
var (
db *DB
)
type DB struct {
*sql.DB
}
func init() {
if err := godotenv.Load(); err != nil {
log.Fatalf("error loading env vars: %s", err)
}
var dbUrl string
flag.StringVar(&dbUrl, "DATABASE_URL", "", "Database URL")
flag.Parse()
if dbUrl == "" {
log.Fatal("DATABASE_URL not set")
}
db = initDB(dbUrl)
}
func initDB(url string) *DB {
db, err := sql.Open("postgres", url)
if err != nil {
log.Fatal(err)
}
// test connection
_, err = db.Exec("SELECT 1")
if err != nil {
log.Fatal(err)
}
// TODO: run migrations
return &DB{DB: db}
}