forked from nixcn/nixcn-cms
Fix config module for unit test
Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
@@ -1,71 +1,12 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
func GetEnv(key string) string {
|
||||
_ = godotenv.Load()
|
||||
upperKey := strings.ToUpper(key)
|
||||
return os.Getenv(upperKey)
|
||||
}
|
||||
|
||||
func SetEnvConf(key string, sub string) {
|
||||
envJoin := strings.Join([]string{key, sub}, "_")
|
||||
env := GetEnv(envJoin)
|
||||
confJoin := strings.Join([]string{key, sub}, ".")
|
||||
orig := Get(confJoin)
|
||||
if env != "" {
|
||||
switch orig.(type) {
|
||||
case string:
|
||||
Set(confJoin, env)
|
||||
case int:
|
||||
conv, err := strconv.Atoi(env)
|
||||
if err != nil {
|
||||
log.Panic("[Config] Error converting string to int: ", err)
|
||||
}
|
||||
Set(confJoin, conv)
|
||||
case bool:
|
||||
switch env {
|
||||
case "true":
|
||||
Set(confJoin, true)
|
||||
case "false":
|
||||
Set(confJoin, false)
|
||||
}
|
||||
case []string:
|
||||
trim := strings.TrimSpace(env)
|
||||
trim = strings.TrimPrefix(trim, "[")
|
||||
trim = strings.TrimSuffix(trim, "]")
|
||||
var envArray []string
|
||||
for _, v := range strings.Split(trim, ",") {
|
||||
trimSub := strings.TrimPrefix(v, "\"")
|
||||
trimSub = strings.TrimSuffix(trimSub, "\"")
|
||||
envArray = append(envArray, trimSub)
|
||||
}
|
||||
Set(confJoin, envArray)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func EnvInit() {
|
||||
var dict = map[string][]string{
|
||||
"server": {"address", "debug_mode", "file_logger", "jwt_secret"},
|
||||
"database": {"type", "host", "name", "username", "password"},
|
||||
}
|
||||
for key, value := range dict {
|
||||
for _, sub := range value {
|
||||
SetEnvConf(key, sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TZ() string {
|
||||
tz := GetEnv("TZ")
|
||||
tz := os.Getenv("TZ")
|
||||
|
||||
if tz == "" {
|
||||
return "Asia/Shanghai"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user