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)
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?