Files
uptimesebi/cmd/api/main.go
T
Sebastian UnterschützandClaude Opus 5.5 e9c7394c8b feat(platform)!: log exclusively as structured json
Request access logs, panics, migration output and fatal errors are now
emitted through the JSON slog handler.

BREAKING CHANGE: UPTIME_LOG_FORMAT is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-21 23:41:57 +01:00

92 lines
2.3 KiB
Go

package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
func main() {
log := platform.NewLogger("api")
if err := run(log, os.Args[1:]); err != nil {
log.Error("exit", "error", err)
os.Exit(1)
}
}
func run(log *slog.Logger, args []string) error {
cfg, err := config.Load[config.API]()
if err != nil {
return err
}
platform.SetLogLevel(cfg.LogLevel)
ctx, stop := platform.SignalContext()
defer stop()
if len(args) > 0 && args[0] == "migrate" {
return migrate(ctx, log, cfg.DatabaseURL, args[1:])
}
if len(args) > 0 && args[0] != "serve" {
return errors.New("usage: api [serve | migrate up|down|status]")
}
deps, err := platform.Connect(ctx, cfg.Common, log)
if err != nil {
return err
}
defer deps.Close()
health := platform.NewHealth(deps.Probes())
r := platform.NewRouter(log)
health.Register(r)
r.StaticFS("/static", web.Static())
r.GET("/", func(c *gin.Context) { web.Render(c, http.StatusOK, web.Index()) })
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
}
func migrate(ctx context.Context, log *slog.Logger, dsn string, args []string) error {
if dsn == "" {
return errors.New("UPTIME_DATABASE_URL is required")
}
log = log.With("task", "migrate")
cmd := "up"
if len(args) > 0 {
cmd = args[0]
}
switch cmd {
case "up":
res, err := migrations.Up(ctx, dsn)
for _, r := range res {
log.Info("migration applied", "migration", r.Source.Version, "file", r.Source.Path, "duration_ms", r.Duration.Milliseconds())
}
if err == nil && len(res) == 0 {
log.Info("schema up to date")
}
return err
case "down":
r, err := migrations.Down(ctx, dsn)
if r != nil {
log.Info("migration rolled back", "migration", r.Source.Version, "file", r.Source.Path, "duration_ms", r.Duration.Milliseconds())
}
return err
case "status":
st, err := migrations.Status(ctx, dsn)
for _, s := range st {
log.Info("migration status", "migration", s.Source.Version, "file", s.Source.Path, "state", string(s.State))
}
return err
}
return errors.New("unknown migrate command " + cmd)
}