112 lines
2.0 KiB
Go
112 lines
2.0 KiB
Go
|
package providers
|
||
|
|
||
|
import (
|
||
|
"github.com/joho/godotenv"
|
||
|
"github.com/kos-v/dsnparser"
|
||
|
"os"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// depth 是 .env 文件的搜索深度
|
||
|
var depth = 8
|
||
|
|
||
|
type defaultConfig struct {
|
||
|
Redis struct {
|
||
|
Addr string
|
||
|
Pass string
|
||
|
}
|
||
|
|
||
|
DB struct {
|
||
|
DSN string
|
||
|
DSN2 string
|
||
|
Driver string
|
||
|
}
|
||
|
|
||
|
GRPC struct {
|
||
|
GrpcListenAddr string
|
||
|
}
|
||
|
|
||
|
JWKS struct {
|
||
|
Url string
|
||
|
}
|
||
|
|
||
|
DebugMode struct {
|
||
|
Enable bool
|
||
|
}
|
||
|
|
||
|
DataScope struct {
|
||
|
ApiKey string
|
||
|
}
|
||
|
|
||
|
MeiliSearch struct {
|
||
|
Host string
|
||
|
ApiKey string
|
||
|
}
|
||
|
|
||
|
OneApi struct {
|
||
|
ApiBase string
|
||
|
ApiKey string
|
||
|
}
|
||
|
}
|
||
|
|
||
|
var Config = defaultConfig{}
|
||
|
|
||
|
func InitConfig() {
|
||
|
envPath := GetEnvFilePath()
|
||
|
_ = godotenv.Load(envPath)
|
||
|
|
||
|
Config.DB.DSN = GetEnv("DB_DSN")
|
||
|
Config.DB.Driver = "postgres"
|
||
|
Config.Redis.Addr = GetEnv("REDIS_ADDR")
|
||
|
Config.Redis.Pass = GetEnv("REDIS_PASS")
|
||
|
Config.GRPC.GrpcListenAddr = GetEnv("LISTEN_ADDR")
|
||
|
Config.JWKS.Url = GetEnv("JWKS_URL")
|
||
|
Config.DebugMode.Enable = GetEnv("DEBUG", "false") == "true"
|
||
|
Config.DataScope.ApiKey = GetEnv("DATASCOPE_API_KEY")
|
||
|
Config.MeiliSearch.Host = GetEnv("MEILISEARCH_HOST")
|
||
|
Config.MeiliSearch.ApiKey = GetEnv("MEILISEARCH_API_KEY")
|
||
|
|
||
|
Config.OneApi.ApiBase = GetEnv("OPENAI_API_BASE")
|
||
|
Config.OneApi.ApiKey = GetEnv("OPENAI_API_KEY")
|
||
|
|
||
|
dsn := dsnparser.Parse(Config.DB.DSN)
|
||
|
var dsn2 = ""
|
||
|
|
||
|
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
|
||
|
}
|
||
|
|
||
|
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
|
||
|
}
|