Atomic Config Reload Swap

Reload configuration atomically using atomic.Value for zero-downtime config updates.

GoConfig Management

Code

gosnippet
16 lines
package main
import ("sync/atomic";"time";"fmt")
type Config struct {
    Port int
    FeatureFlags map[string]bool
}
var config atomic.Value
func loadConfig() Config { return config.Load().(Config) }
func reloadConfig(newCfg Config) { config.Store(&newCfg) }
func main() {
    config.Store(&Config{Port: 8080})
    go func() {
        for { time.Sleep(time.Minute); reloadConfig(Config{Port: 9090}) }
    }()
    fmt.Println(loadConfig().Port)
}

How it works

Structurally, expect the functions loadConfig, reloadConfig and main and nothing else.

Repetition is confined to for { time.Sleep(time.Minute); reloadConfig(Config{Port: 9090}) } — the rest of the file is straight-line. The task is handed to a goroutine and runs concurrently.

Applying it

Entry signature: func loadConfig() Config

The demo flow inside main is reloadConfig and loadConfig — run the file to see it end to end.

Statements that matter

func loadConfig() Config { return config.Load().(Config) }
func reloadConfig(newCfg Config) { config.Store(&newCfg) }
func main() {
config.Store(&Config{Port: 8080})
go func() {
for { time.Sleep(time.Minute); reloadConfig(Config{Port: 9090}) }
}()
fmt.Println(loadConfig().Port)
}

Interactive Tools for This Topic

FAQ

How do you run Atomic Config Reload Swap?
Run the file on its own; every call resolves against the standard surface it already imports.