82 lines
2.1 KiB
Go
82 lines
2.1 KiB
Go
package conf
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
|
|
"github.com/joho/godotenv"
|
|
)
|
|
|
|
// Config 配置结构体
|
|
type Config struct {
|
|
AccessKeyID string
|
|
AccessKeySecret string
|
|
Region string
|
|
Endpoint string
|
|
}
|
|
|
|
// LoadConfig 加载配置
|
|
func LoadConfig() (*Config, error) {
|
|
// 尝试加载多个可能的配置文件
|
|
configFiles := []string{
|
|
".env", // 根目录的.env文件
|
|
"conf/alibabacloud.env", // 阿里云配置文件
|
|
"alibabacloud.env", // 根目录的阿里云配置文件
|
|
}
|
|
|
|
// 按顺序尝试加载配置文件
|
|
for _, configFile := range configFiles {
|
|
if err := godotenv.Load(configFile); err == nil {
|
|
fmt.Printf("成功加载配置文件: %s\n", configFile)
|
|
break
|
|
}
|
|
}
|
|
|
|
config := &Config{
|
|
AccessKeyID: getEnv("ALIBABA_CLOUD_ACCESS_KEY_ID", ""),
|
|
AccessKeySecret: getEnv("ALIBABA_CLOUD_ACCESS_KEY_SECRET", ""),
|
|
Region: getEnv("ALIBABA_CLOUD_REGION", "cn-shanghai"),
|
|
Endpoint: getEnv("ALIBABA_CLOUD_ENDPOINT", "green.cn-shanghai.aliyuncs.com"),
|
|
}
|
|
|
|
return config, nil
|
|
}
|
|
|
|
// LoadConfigFromFile 从指定文件加载配置
|
|
func LoadConfigFromFile(configFile string) (*Config, error) {
|
|
// 加载指定的配置文件
|
|
if err := godotenv.Load(configFile); err != nil {
|
|
return nil, fmt.Errorf("加载配置文件失败 %s: %v", configFile, err)
|
|
}
|
|
|
|
fmt.Printf("成功加载配置文件: %s\n", configFile)
|
|
|
|
config := &Config{
|
|
AccessKeyID: getEnv("ALIBABA_CLOUD_ACCESS_KEY_ID", ""),
|
|
AccessKeySecret: getEnv("ALIBABA_CLOUD_ACCESS_KEY_SECRET", ""),
|
|
Region: getEnv("ALIBABA_CLOUD_REGION", "cn-shanghai"),
|
|
Endpoint: getEnv("ALIBABA_CLOUD_ENDPOINT", "green.cn-shanghai.aliyuncs.com"),
|
|
}
|
|
|
|
return config, nil
|
|
}
|
|
|
|
// getEnv 获取环境变量,如果不存在则返回默认值
|
|
func getEnv(key, defaultValue string) string {
|
|
if value := os.Getenv(key); value != "" {
|
|
return value
|
|
}
|
|
return defaultValue
|
|
}
|
|
|
|
// getEnvAsInt 获取环境变量并转换为整数
|
|
func getEnvAsInt(key string, defaultValue int) int {
|
|
if value := os.Getenv(key); value != "" {
|
|
if intValue, err := strconv.Atoi(value); err == nil {
|
|
return intValue
|
|
}
|
|
}
|
|
return defaultValue
|
|
}
|