Dynamically Updating Configuration in a Running Goroutine
Owner: SnippetBot
Created: 2026-09-12 00:01:05
Size: 1.74 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"fmt"
"time"
)
// Config represents the application configuration
type Config struct {
LogLevel string
MaxRetries int
WorkerCount int
}
// ConfigService simulates a long-running service that consumes a config channel
func ConfigService(configUpdates <-chan Config, shutdown <-chan struct{}) {
currentConfig := Config{
LogLevel: "INFO",
MaxRetries: 3,
WorkerCount: 1,
}
fmt.Printf("[ConfigService] Initial config: %+v
", currentConfig)
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case newConfig := <-configUpdates:
currentConfig = newConfig
fmt.Printf("[ConfigService] Configuration updated: %+v
", currentConfig)
// In a real application, you might re-initialize components here
case <-ticker.C:
// Simulate periodic work using the current configuration
fmt.Printf("[ConfigService] Doing work with config (LogLevel: %s, Workers: %d)...
",
currentConfig.LogLevel, currentConfig.WorkerCount)
case <-shutdown:
fmt.Println("[ConfigService] Shutting down.")
return
}
}
}
func main() {
configCh := make(chan Config)
shutdownCh := make(chan struct{})
go ConfigService(configCh, shutdownCh)
// Simulate sending new configurations
time.Sleep(3 * time.Second)
fmt.Println("[Main] Sending config update 1...")
configCh <- Config{LogLevel: "DEBUG", MaxRetries: 5, WorkerCount: 2}
time.Sleep(4 * time.Second)
fmt.Println("[Main] Sending config update 2...")
configCh <- Config{LogLevel: "ERROR", MaxRetries: 10, WorkerCount: 5}
time.Sleep(5 * time.Second)
fmt.Println("[Main] Signaling ConfigService to shut down.")
close(shutdownCh)
// Give service a moment to shut down
time.Sleep(500 * time.Millisecond)
fmt.Println("[Main] Application finished.")
}