61 lines
890 B
Go
61 lines
890 B
Go
|
package config
|
||
|
|
||
|
import (
|
||
|
"github.com/joho/godotenv"
|
||
|
"os"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// depth 是 .env 文件的搜索深度
|
||
|
var depth = 8
|
||
|
|
||
|
func InitConfig() {
|
||
|
envPath := GetEnvFilePath()
|
||
|
_ = godotenv.Load(envPath)
|
||
|
|
||
|
Auth = auth{
|
||
|
Pass: GetEnv("AUTH_PASS"),
|
||
|
}
|
||
|
|
||
|
Dir = dir{
|
||
|
Dir: GetEnv("LOG_DIR"),
|
||
|
}
|
||
|
|
||
|
Gin = gin{
|
||
|
Port: GetEnv("PORT"),
|
||
|
}
|
||
|
}
|
||
|
func GetEnv(key string, defaultValue ...string) string {
|
||
|
r := os.Getenv(key)
|
||
|
|
||
|
if len(r) == 0 && len(defaultValue) > 0 {
|
||
|
return defaultValue[0]
|
||
|
} else {
|
||
|
return r
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func GetEnvFilePath() string {
|
||
|
|
||
|
var path string
|
||
|
|
||
|
if os.Getenv("ENV_PATH") != "" {
|
||
|
path = os.Getenv("ENV_PATH")
|
||
|
|
||
|
return path
|
||
|
}
|
||
|
|
||
|
var pathOptions []string
|
||
|
for i := 0; i <= depth; i++ {
|
||
|
pathOptions = append(pathOptions, strings.Repeat("../", i)+".env")
|
||
|
}
|
||
|
for _, p := range pathOptions {
|
||
|
if _, err := os.Stat(p); err == nil {
|
||
|
path = p
|
||
|
break
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return path
|
||
|
}
|