Problem Outline:
This code snippet loads data from files into a map during startup. However, it faces an issue when encountering errors during file loading. The issue arises because the code clears the map before loading each new file, which can lead to data loss if an error occurs and the previous map state is not preserved.
Proposed Solution:
To overcome this issue, a more straightforward approach can be adopted:
Implementation:
type CustomerConfig struct {
Data map[string]bool
LoadedAt time.Time
}
func loadConfig() (*CustomerConfig, error) {
cfg := &CustomerConfig{
Data: map[string]bool{},
LoadedAt: time.Now(),
}
// Load files and populate cfg.Data
// Return error if encountered
return cfg, nil
}
type ConfigCache struct {
configMu sync.RWMutex
config *CustomerConfig
closeCh chan struct{}
}
func NewConfigCache() (*ConfigCache, error) {
cfg, err := loadConfig()
if err != nil {
return nil, err
}
cc := &ConfigCache{
config: cfg,
closeCh: make(chan struct{}),
}
go cc.refresher()
return cc, nil
}
func (cc *ConfigCache) refresher() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Check for changes
changes := false // Implement logic to detect changes
if !changes {
continue
}
cfg, err := loadConfig()
if err != nil {
log.Printf("Failed to load config: %v", err)
continue
}
cc.configMu.Lock()
cc.config = cfg
cc.configMu.Unlock()
case <-cc.closeCh:
return
}
}
}
func (cc *ConfigCache) Stop() {
close(cc.closeCh)
}
func (cc *ConfigCache) GetConfig() *CustomerConfig {
cc.configMu.RLock()
defer cc.configMu.RUnlock()
return cc.config
}
Usage:
cc, err := NewConfigCache()
if err != nil {
// Handle error
}
cfg := cc.GetConfig() // Access the latest configuration
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3