forked from nixcn/nixcn-cms
Add jwt crypto module, support unit test for config module
Signed-off-by: Asai Neko<sugar@sne.moe>
This commit is contained in:
@@ -2,17 +2,29 @@ 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("config.yaml")
|
||||
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)
|
||||
@@ -24,17 +36,9 @@ func Init() {
|
||||
}
|
||||
|
||||
func Get(key string) any {
|
||||
viper.SetConfigFile("config.yaml")
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
log.Fatal("[Config] Error reading config: ", err)
|
||||
}
|
||||
return viper.Get(key)
|
||||
}
|
||||
|
||||
func Set(key string, value any) {
|
||||
viper.SetConfigFile("config.yaml")
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
log.Fatal("[Config] Error reading config: ", err)
|
||||
}
|
||||
viper.Set(key, value)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ var serverDef = server{
|
||||
Address: ":8000",
|
||||
DebugMode: false,
|
||||
FileLogger: false,
|
||||
JwtSecret: "something",
|
||||
}
|
||||
|
||||
var databaseDef = database{
|
||||
|
||||
@@ -54,7 +54,7 @@ func SetEnvConf(key string, sub string) {
|
||||
|
||||
func EnvInit() {
|
||||
var dict = map[string][]string{
|
||||
"server": {"address", "debug_mode", "file_logger"},
|
||||
"server": {"address", "debug_mode", "file_logger", "jwt_secret"},
|
||||
"database": {"type", "host", "name", "username", "password"},
|
||||
}
|
||||
for key, value := range dict {
|
||||
|
||||
@@ -9,6 +9,7 @@ type server struct {
|
||||
Address string `yaml:"address"`
|
||||
DebugMode bool `yaml:"debug_mode"`
|
||||
FileLogger bool `yaml:"file_logger"`
|
||||
JwtSecret string `yaml:"jwt_secret"`
|
||||
}
|
||||
|
||||
type database struct {
|
||||
|
||||
Reference in New Issue
Block a user