How to Implement Configuration Hot Reload in Go

Go requires a custom file watcher to implement configuration hot reloading since it lacks native support for this feature.

Go does not natively support configuration hot reloading; you must implement a file watcher that triggers a manual reload of your configuration struct. Use the os/signal package to catch file changes or a third-party watcher like fsnotify to detect updates, then re-parse your config file and update your application state without restarting.

package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var config *Config

func main() {
	config = loadConfig("config.yaml")
	go watchConfig("config.yaml")
	
	// Simulate long-running process
	for {
		fmt.Println("Running with config:", config)
		time.Sleep(1 * time.Second)
	}
}

func loadConfig(path string) *Config {
	// Parse your YAML/JSON here
	return &Config{Value: "initial"}
}

func watchConfig(path string) {
	// Simple polling approach (replace with fsnotify for production)
	ticker := time.NewTicker(2 * time.Second)
	defer ticker.Stop()
	
	for range ticker.C {
		if newConfig := loadConfig(path); newConfig != nil {
			// Update global config atomically
			config = newConfig
			fmt.Println("Config reloaded")
		}
	}
}

type Config struct {
	Value string
}