Files
2026-08-06 18:26:45 +12:00

86 lines
2.3 KiB
Go

// Command server is the whole app: it serves the JSON API and the embedded
// Svelte SPA from one binary, and applies DB migrations on startup.
package main
import (
"context"
"fmt"
"io/fs"
"log"
"net/http"
"strings"
"time"
"vlog/internal/auth"
"vlog/internal/config"
"vlog/internal/db"
"vlog/internal/handlers"
"vlog/internal/storage"
)
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatalf("config: %v", err)
}
ctx := context.Background()
database, err := db.Connect(cfg.DBDriver, cfg.DatabaseURL)
if err != nil {
log.Fatalf("database: %v", err)
}
defer database.Close()
store, err := newStorage(ctx, cfg)
if err != nil {
log.Fatalf("storage: %v", err)
}
// Only require Secure cookies when we're actually serving over https —
// lets this run over plain http for local dev.
secureCookies := strings.HasPrefix(cfg.PublicBaseURL, "https://")
authenticator, err := auth.NewAuthenticator(ctx, cfg.OIDCIssuerURL, cfg.OIDCClientID, cfg.OIDCClientSecret, cfg.OIDCRedirectURL, secureCookies)
if err != nil {
log.Fatalf("oidc: %v", err)
}
h := handlers.New(database, store, authenticator, cfg.JWTSigningSecret, secureCookies)
mux := http.NewServeMux()
registerRoutes(mux, h)
staticFS, err := fs.Sub(frontendFS, "web")
if err != nil {
log.Fatalf("frontend assets: %v", err)
}
mux.Handle("/", spaHandler(staticFS))
srv := &http.Server{
Addr: ":" + cfg.Port,
Handler: logMiddleware(mux),
ReadHeaderTimeout: 10 * time.Second,
}
log.Printf("listening on :%s", cfg.Port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("server: %v", err)
}
}
// newStorage picks the file storage backend based on STORAGE_DRIVER: "s3"
// (production) or "local" (writes to disk — for testing without a real S3
// bucket). Handlers depend only on the storage.Storage interface, so
// nothing else in the app needs to know which one is active.
func newStorage(ctx context.Context, cfg *config.Config) (storage.Storage, error) {
switch cfg.StorageDriver {
case "s3":
return storage.NewS3(ctx, cfg.AWSRegion, cfg.S3Bucket)
case "local":
return storage.NewLocal(cfg.LocalStoragePath)
default:
return nil, fmt.Errorf("invalid STORAGE_DRIVER %q (must be s3 or local)", cfg.StorageDriver)
}
}