framework_v2/internal/providers/config.go
2024-07-14 19:24:45 +08:00

115 lines
2.2 KiB
Go

package providers
import (
"github.com/joho/godotenv"
"github.com/kos-v/dsnparser"
"os"
"strings"
)
// depth 是 .env 文件的搜索深度
var depth = 8
type GlobalConfig struct {
Redis struct {
Addr string
Pass string
}
DB struct {
DSN string
DSN2 string
Driver string
}
ListenAddr struct {
GRPC string
HTTP string
}
JWKS struct {
Url string
}
DebugMode struct {
Enable bool
}
S3 struct {
Endpoint string
Bucket string
AccessKeyID string
SecretAccessKey string
UseSSL bool
}
}
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
}
func provideConfig() *GlobalConfig {
envPath := GetEnvFilePath()
_ = godotenv.Load(envPath)
var Config = &GlobalConfig{}
Config.DB.DSN = GetEnv("DB_DSN")
Config.DB.Driver = "postgres"
Config.Redis.Addr = GetEnv("REDIS_ADDR")
Config.Redis.Pass = GetEnv("REDIS_PASS")
Config.ListenAddr.GRPC = GetEnv("GRPC_LISTEN_ADDR")
Config.ListenAddr.HTTP = GetEnv("HTTP_LISTEN_ADDR")
Config.JWKS.Url = GetEnv("JWKS_URL")
Config.DebugMode.Enable = GetEnv("DEBUG", "false") == "true"
Config.S3.Endpoint = GetEnv("S3_ENDPOINT")
Config.S3.Bucket = GetEnv("S3_BUCKET")
Config.S3.AccessKeyID = GetEnv("S3_ACCESS_KEY_ID")
Config.S3.SecretAccessKey = GetEnv("S3_SECRET_ACCESS_KEY")
Config.S3.UseSSL = GetEnv("S3_USE_SSL", "true") == "true"
dsn := dsnparser.Parse(Config.DB.DSN)
var dsn2 = ""
dsn2 += "host=" + dsn.GetHost()
dsn2 += " port=" + dsn.GetPort()
dsn2 += " user=" + dsn.GetUser()
dsn2 += " password=" + dsn.GetPassword()
dsn2 += " dbname=" + dsn.GetPath()
if dsn.HasParam("sslmode") {
dsn2 += " sslmode=" + dsn.GetParam("sslmode")
}
Config.DB.DSN2 = dsn2
return Config
}
func init() {
Must(Container.Provide(provideConfig))
}