Go Config Watch
In this tutorial, you'll learn about Go Config: Hot Reload. We cover key concepts, practical examples, and best practices.
Config hot reload -- Watch configuration files for changes and reload without restarting the application.
The Problem
Restarting the application on every config change causes downtime. Use fsnotify or viper.WatchConfig to detect file changes and reload configuration live.
Wrong
func readConfig() Config {
// Read once at startup
var cfg Config
yaml.Unmarshal(data, &cfg)
return cfg
}
Output:
// Config changes require app restart
Right
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
slog.Info("config changed", "file", e.Name)
applyConfig(viper.AllSettings())
})
// Or with fsnotify directly:
watcher, _ := fsnotify.NewWatcher()
go func() {
for event := range watcher.Events {
if event.Op&fsnotify.Write == fsnotify.Write {
reloadConfig(event.Name)
}
}
}()
Output:
// Config changes applied without restart
Prevention
- Use viper.WatchConfig() for Viper-based hot reload
- Use fsnotify for custom config reload logic
- Use atomic.Value for thread-safe config swap
- Signal old connections to refresh with new config
- Test config reload under load
Common Mistakes with config watch
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro