underbbs/config/config.go

56 lines
1.2 KiB
Go
Raw Normal View History

2025-01-05 03:45:22 +00:00
package config
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"forge.lightcrystal.systems/nilix/underbbs/models"
)
func getConfigLocation() string {
home := os.Getenv("HOME")
appdata := os.Getenv("APPDATA")
switch runtime.GOOS {
case "windows":
return filepath.Join(appdata, "underbbs")
case "darwin":
return filepath.Join(home, "Library", "Application Support", "underbbs")
case "plan9":
return filepath.Join(home, "lib", "underbbs")
default:
return filepath.Join(home, ".config", "underbbs")
}
}
func ensureConfigLocationExists() {
fileInfo, err := os.Stat(getConfigLocation())
if os.IsNotExist(err) {
os.MkdirAll(getConfigLocation(), os.ModePerm)
} else if !fileInfo.IsDir() {
panic("Config location is not a directory!")
}
}
func LoadConfig() (models.GlobalSettings, error) {
var settings models.GlobalSettings
ensureConfigLocationExists()
cfgdir := getConfigLocation()
// get config from config fle based on adapter
content, err := ioutil.ReadFile(filepath.Join(cfgdir, "config.json"))
if err != nil {
return settings, err
}
err = json.Unmarshal(content, &settings)
if err != nil {
return settings, err
}
return settings, nil
}