85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
// Command dogama runs the DoGaMa main application.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
catalogdata "git.zaynet.fr/DoGaMa/DoGaMa-serv/catalog"
|
|
"git.zaynet.fr/DoGaMa/DoGaMa-serv/internal/auth"
|
|
"git.zaynet.fr/DoGaMa/DoGaMa-serv/internal/catalog"
|
|
"git.zaynet.fr/DoGaMa/DoGaMa-serv/internal/persistence/sqlite"
|
|
"git.zaynet.fr/DoGaMa/DoGaMa-serv/internal/web"
|
|
)
|
|
|
|
func main() {
|
|
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
|
if err := run(logger); err != nil {
|
|
logger.Error("application stopped", "event", "application.failed", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run(logger *slog.Logger) error {
|
|
listenAddress := environment("DOGAMA_LISTEN_ADDRESS", ":8080")
|
|
databasePath := environment("DOGAMA_DATABASE_PATH", "dogama.db")
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
|
defer stop()
|
|
db, err := sqlite.Open(ctx, databasePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer db.Close()
|
|
snapshots, err := catalog.LoadFS(catalogdata.Files, ".")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
repository := sqlite.NewRepository(db)
|
|
if err := repository.Sync(ctx, snapshots); err != nil {
|
|
return err
|
|
}
|
|
logger.Info("local catalog synchronized", "event", "catalog.synchronized", "template_count", len(snapshots))
|
|
handler, err := web.NewHandlerWithRepository(auth.New(db), repository, logger)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
server := &http.Server{
|
|
Addr: listenAddress,
|
|
Handler: handler,
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
ReadTimeout: 15 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
}
|
|
errCh := make(chan error, 1)
|
|
go func() {
|
|
logger.Info("application listening", "event", "application.started", "address", listenAddress)
|
|
errCh <- server.ListenAndServe()
|
|
}()
|
|
select {
|
|
case err := <-errCh:
|
|
if errors.Is(err, http.ErrServerClosed) {
|
|
return nil
|
|
}
|
|
return err
|
|
case <-ctx.Done():
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
return server.Shutdown(shutdownCtx)
|
|
}
|
|
}
|
|
|
|
func environment(name, fallback string) string {
|
|
if value := os.Getenv(name); value != "" {
|
|
return value
|
|
}
|
|
return fallback
|
|
}
|