clean up main.go

This commit is contained in:
2026-02-09 04:15:11 -08:00
parent b9a7a972e2
commit 38adb391be
2 changed files with 19 additions and 51 deletions

View File

@@ -21,9 +21,18 @@ func CreateAllTables() error {
return CreateSessionsTable() return CreateSessionsTable()
} }
func GetDbUrl() string {
host := os.Getenv("PGHOST")
port := os.Getenv("PGPORT")
user := os.Getenv("PGUSER")
pass := os.Getenv("PGPASSWORD")
return fmt.Sprintf("postgres://%s:%s@%s:%s", user, pass, host, port)
}
func CreateDB() error { func CreateDB() error {
conn, err := pgx.Connect(context.Background(), conn, err := pgx.Connect(context.Background(),
"postgres://postgres:postgres@localhost:5432", GetDbUrl(),
) )
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Cannot connect to PostgreSQL: %v\n", err) fmt.Fprintf(os.Stderr, "Cannot connect to PostgreSQL: %v\n", err)

59
main.go
View File

@@ -2,10 +2,8 @@ package main
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"os" "os"
"path/filepath"
"muzi/db" "muzi/db"
"muzi/web" "muzi/web"
@@ -13,64 +11,25 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
) )
func dirCheck(path string) error { func check(msg string, err error) {
_, err := os.Stat(path)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { fmt.Fprintf(os.Stderr, "Error %s: %v\n", msg, err)
os.MkdirAll(path, os.ModePerm) os.Exit(1)
} else {
fmt.Fprintf(os.Stderr, "Error checking dir: %s: %v\n", path, err)
return err
}
} }
return nil
} }
func main() { func main() {
zipDir := filepath.Join(".", "imports", "spotify", "zip") check("ensuring muzi DB exists", db.CreateDB())
extDir := filepath.Join(".", "imports", "spotify", "extracted")
dirs := []string{zipDir, extDir}
for _, dir := range dirs {
err := dirCheck(dir)
if err != nil {
fmt.Fprintf(os.Stderr, "Error checking dir: %s: %v\n", dir, err)
return
}
}
err := db.CreateDB()
if err != nil {
fmt.Fprintf(os.Stderr, "Error ensuring muzi DB exists: %v\n", err)
return
}
var err error
db.Pool, err = pgxpool.New( db.Pool, err = pgxpool.New(
context.Background(), context.Background(),
"postgres://postgres:postgres@localhost:5432/muzi", fmt.Sprintf(db.GetDbUrl(), "/muzi"),
) )
if err != nil { check("connecting to muzi database", err)
fmt.Fprintf(os.Stderr, "Cannot connect to muzi database: %v\n", err)
return
}
defer db.Pool.Close() defer db.Pool.Close()
err = db.CreateAllTables() check("ensuring all tables exist", db.CreateAllTables())
if err != nil { check("cleaning expired sessions", db.CleanupExpiredSessions())
fmt.Fprintf(os.Stderr, "Error ensuring all tables exist: %v\n", err)
return
}
err = db.CleanupExpiredSessions()
if err != nil {
fmt.Fprintf(os.Stderr, "Error cleaning expired sessions: %v\n", err)
return
}
/*
err = migrate.ImportSpotify(1)
if err != nil {
return
}
*/
web.Start() web.Start()
} }