Atomic Config Reload Swap
Reload configuration atomically using atomic.Value for zero-downtime config updates.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.