chore(config): merge userConfig with defaultConfig and add a lock (#164)

* chore(config): merge userConfig with defaultConfig and add a lock

* chore(config): remove lock for LoadConfig
This commit is contained in:
Aveline
2025-02-17 20:12:34 +01:00
committed by GitHub
parent cd333c4ebc
commit 69461140e3
5 changed files with 11 additions and 34 deletions

View File

@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"os"
"sync"
)
type WakeOnLanDevice struct {
@@ -40,25 +41,28 @@ var defaultConfig = &Config{
DisplayOffAfterSec: 1800, // 30 minutes
}
var config *Config
var (
config *Config
configLock = &sync.Mutex{}
)
func LoadConfig() {
if config != nil {
logger.Info("config already loaded, skipping")
return
}
file, err := os.Open(configPath)
if err != nil {
logger.Debug("default config file doesn't exist, using default")
config = defaultConfig
return
}
defer file.Close()
var loadedConfig Config
// load and merge the default config with the user config
loadedConfig := *defaultConfig
if err := json.NewDecoder(file).Decode(&loadedConfig); err != nil {
logger.Errorf("config file JSON parsing failed, %v", err)
config = defaultConfig
return
}
@@ -66,6 +70,9 @@ func LoadConfig() {
}
func SaveConfig() error {
configLock.Lock()
defer configLock.Unlock()
file, err := os.Create(configPath)
if err != nil {
return fmt.Errorf("failed to create config file: %w", err)