Files
uptimesebi/internal/platform/router.go
T
Sebastian UnterschützandClaude Opus 5.5 c485d1a96f feat(platform): tag requests, logs and api errors with a request id
A well-formed X-Request-ID from a proxy is kept, otherwise a UUIDv7 is
generated. The ID is echoed in the response header, added to every log
record written with the request context and returned in API error
bodies.

Closes #44

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

65 lines
1.7 KiB
Go

package platform
import (
"io"
"log/slog"
"net/http"
"runtime/debug"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
)
var quietPaths = map[string]bool{"/healthz": true, "/readyz": true}
// NewRouter returns a gin engine that assigns request IDs, logs requests and
// panics through log as JSON and writes nothing to stdout itself.
func NewRouter(log *slog.Logger) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = io.Discard
gin.DefaultErrorWriter = io.Discard
r := gin.New()
r.Use(requestid.Middleware(), accessLog(log), recovery(log))
return r
}
func accessLog(log *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
if quietPaths[c.Request.URL.Path] && c.Writer.Status() < 500 {
return
}
attrs := []any{
"method", c.Request.Method,
"path", c.Request.URL.Path,
"route", c.FullPath(),
"status", c.Writer.Status(),
"duration_ms", time.Since(start).Milliseconds(),
"bytes", c.Writer.Size(),
"client_ip", c.ClientIP(),
}
if len(c.Errors) > 0 {
attrs = append(attrs, "errors", c.Errors.Errors())
}
level := slog.LevelInfo
switch {
case c.Writer.Status() >= 500:
level = slog.LevelError
case c.Writer.Status() >= 400:
level = slog.LevelWarn
}
log.Log(c.Request.Context(), level, "http request", attrs...)
}
}
func recovery(log *slog.Logger) gin.HandlerFunc {
return gin.CustomRecoveryWithWriter(io.Discard, func(c *gin.Context, err any) {
log.ErrorContext(c.Request.Context(), "panic",
"error", err, "path", c.Request.URL.Path, "stack", string(debug.Stack()))
c.AbortWithStatus(http.StatusInternalServerError)
})
}