Request counting and crash collection for telemetry reporting.
import (
"hatmax.adrianpk.com/middleware"
"hatmax.adrianpk.com/settings"
"hatmax.adrianpk.com/telemetry"
)
// Create collectors
counter := telemetry.NewCounter()
crashes := telemetry.NewCrashCollector()
// Register settings schemas with your registry
registry := settings.NewRegistry()
telemetry.RegisterSchemas(registry)
// Apply middleware to your router
router.Use(middleware.TelemetryRecovery(crashes))
router.Use(middleware.TelemetryCounter(counter))
// Periodically collect and send data
mode, _ := settingsService.GetString(ctx, telemetry.KeyMode)
if mode != telemetry.ModeOff {
requests := counter.GetAndResetRequests()
crashEvents := crashes.GetAndResetCrashes()
// Send to your telemetry endpoint...
}type RequestCounter interface {
IncrementRequests()
GetAndResetRequests() int64
}NewCounter() *AtomicCounter- creates a thread-safe counterIncrementRequests()- increments by one (atomic)GetAndResetRequests() int64- returns count and resets to zero (atomic swap)
type CrashRecorder interface {
RecordPanic(message, endpoint, method string)
}
type CrashEvent struct {
Type string // "panic"
Message string // sanitized, max 200 chars
Stack []string // max 10 frames
Endpoint string
Method string
Count int64 // deduplicated count
FirstSeen string // RFC3339
LastSeen string // RFC3339
}NewCrashCollector() *CrashCollector- creates a collectorRecordPanic(message, endpoint, method string)- records with deduplication by message+endpointGetAndResetCrashes() []CrashEvent- returns all events and clears
Predefined schemas for telemetry configuration:
// Key constants
telemetry.KeyMode // "telemetry.mode"
telemetry.KeyInstanceID // "telemetry.instance_id"
// Mode constants
telemetry.ModeOff // "off" - no telemetry
telemetry.ModeBasic // "basic" - ping only (default)
telemetry.ModeFull // "full" - ping + request count
telemetry.ModeDebug // "debug" - full + crash reportsSchemas- slice ofsettings.Schemafor registrationRegisterSchemas(r *settings.Registry)- helper to register all schemas
The telemetry middleware is in the middleware package:
// Count every request
router.Use(middleware.TelemetryCounter(counter))
// Catch panics and record them (also returns 500)
router.Use(middleware.TelemetryRecovery(crashes))Both middleware functions accept nil safely (no-op).