Files
nixcn-cms/config/config.go
2025-12-23 18:11:31 +08:00

45 lines
934 B
Go

package config
import (
"log"
"os"
"github.com/spf13/viper"
)
func Init() {
// Set config path by env
confPath := os.Getenv("CONFIG_PATH")
if confPath == "" {
confPath = "config.yaml"
}
// Read global config
viper.SetConfigFile(confPath)
viper.SetDefault("Server", serverDef)
viper.SetDefault("Database", databaseDef)
conf := &config{}
if err := viper.ReadInConfig(); err != nil {
// Dont generate config when using dev mode
if os.Getenv("GO_ENV") == "test" || os.Getenv("CONFIG_PATH") != "" {
log.Fatalf("[Config] failed to read config %s: %v", confPath, err)
}
log.Println("Can't read config, trying to modify!")
if err := viper.WriteConfig(); err != nil {
log.Fatal("[Config] Error writing config: ", err)
}
}
if err := viper.Unmarshal(conf); err != nil {
log.Fatal(err)
}
}
func Get(key string) any {
return viper.Get(key)
}
func Set(key string, value any) {
viper.Set(key, value)
}