Add Database Connection and Migration

This commit is contained in:
Samuel Lorch 2024-05-04 02:19:45 +02:00
parent 560b25419f
commit cd3d6ee256
5 changed files with 113 additions and 8 deletions

View file

@ -11,6 +11,11 @@ import (
"os/signal"
"time"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/pgx/v5"
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/jackc/pgx/v5/pgxpool"
"git.lastassault.de/speatzle/morffix/config"
)
@ -18,7 +23,9 @@ var conf config.Config
var templates *template.Template
func Start(_conf config.Config, tmplFS embed.FS, staticFS embed.FS) {
var db *pgxpool.Pool
func Start(_conf config.Config, tmplFS embed.FS, staticFS embed.FS, migrationsFS embed.FS) {
conf = _conf
// Static Files
@ -32,6 +39,35 @@ func Start(_conf config.Config, tmplFS embed.FS, staticFS embed.FS) {
}
templates = t
slog.Info("Connecting to Database...")
db, err = pgxpool.New(context.Background(), "postgres://"+conf.Server.Database)
if err != nil {
slog.Error("Unable to create connection pool", "err", err)
return
}
defer db.Close()
slog.Info("Connected to Database, Starting Migration")
driver, err := iofs.New(migrationsFS, "migrations")
if err != nil {
slog.Error("Unable to Create Migration Driver", "err", err)
return
}
m, err := migrate.NewWithSourceInstance("iofs", driver, "pgx5://"+conf.Server.Database)
if err != nil {
slog.Error("Unable to Setup migration", "err", err)
return
}
err = m.Up()
if err != nil {
slog.Error("Unable to Migrate", "err", err)
return
}
slog.Info("Migration Done")
mux := http.NewServeMux()
mux.HandleFunc("/worker", handleWorkerWebsocket)
mux.Handle("/static/", fs)