package main import ( "context" "log/slog" "time" "github.com/fsnotify/fsnotify" ) func watchConfig(ctx context.Context, watcher *fsnotify.Watcher, config *Config) { const debounce = 100 * time.Millisecond var timer *time.Timer var pending <-chan time.Time defer func() { if timer != nil { timer.Stop() } }() for { select { case event, ok := <-watcher.Events: if !ok { return } if !event.Has(fsnotify.Create | fsnotify.Write | fsnotify.Rename | fsnotify.Remove) { continue } if timer == nil { timer = time.NewTimer(debounce) } else { timer.Reset(debounce) } pending = timer.C case <-pending: pending = nil if err := config.Reload(); err != nil { slog.ErrorContext(ctx, "failed to reload configuration", slog.Any("error", err)) continue } slog.LogAttrs(ctx, slog.LevelInfo, "configuration reloaded", configLogArgs(config)...) case err, ok := <-watcher.Errors: if !ok { return } slog.ErrorContext(ctx, "fs watcher error", slog.Any("error", err)) case <-ctx.Done(): return } } }