How do I hot-reload configuration at runtime in Go?

Hot-reloading configuration at runtime in Go can significantly enhance the flexibility of applications. This technique allows you to modify configuration settings without the need to restart the application. Below is an example demonstrating how to implement this feature using Go's file watching capabilities.

package main import ( "encoding/json" "fmt" "github.com/fsnotify/fsnotify" "io/ioutil" "log" "os" "time" ) type Config struct { AppName string `json:"app_name"` Port int `json:"port"` } var config Config func loadConfig() { file, err := os.Open("config.json") if err != nil { log.Fatalf("Failed to open config file: %s", err) } defer file.Close() byteValue, _ := ioutil.ReadAll(file) json.Unmarshal(byteValue, &config) fmt.Printf("Config loaded: %+v\n", config) } func watchConfig(path string) { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() err = watcher.Add(path) if err != nil { log.Fatal(err) } done := make(chan bool) go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } if event.Op&fsnotify.Write == fsnotify.Write { fmt.Println("Config file modified, reloading...") loadConfig() } case err, ok := <-watcher.Errors: if !ok { return } log.Println("Error:", err) } } }() <-done } func main() { loadConfig() go watchConfig("config.json") // Simulated application running for { time.Sleep(10 * time.Second) } }

hot-reload configuration runtime Go fsnotify json file watching