mirror of
https://github.com/luckfox-eng29/kvm.git
synced 2026-01-18 03:28:19 +01:00
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:
15
config.go
15
config.go
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user