Files
mail_api_go/pkg/api/config.go
huangzhenpc a8d25054fc sdd
2025-05-23 23:08:02 +08:00

91 lines
2.0 KiB
Go

package api
import (
"fmt"
"io/ioutil"
"os"
"gopkg.in/yaml.v3"
)
// Config 保存应用程序配置
type Config struct {
API struct {
BaseURL string `yaml:"base_url"`
DisableProxy bool `yaml:"disable_proxy"`
} `yaml:"api"`
User struct {
DefaultDomain string `yaml:"default_domain"`
DefaultPassword string `yaml:"default_password"`
DefaultQuota int64 `yaml:"default_quota"`
} `yaml:"user"`
Auth struct {
Basic struct {
AdminUsername string `yaml:"username"`
AdminPassword string `yaml:"password"`
} `yaml:"basic"`
APIKey string `yaml:"api_key"`
} `yaml:"auth"`
}
// LoadConfig 从指定路径加载配置文件
func LoadConfig(path string) (*Config, error) {
// 如果未指定路径,使用默认路径
if path == "" {
// 尝试在当前目录和上一级目录查找配置文件
candidates := []string{
"config.yaml",
"config/config.yaml",
"../config/config.yaml",
}
for _, candidate := range candidates {
if _, err := os.Stat(candidate); err == nil {
path = candidate
break
}
}
if path == "" {
return nil, fmt.Errorf("未找到配置文件")
}
}
// 读取配置文件
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("读取配置文件失败: %w", err)
}
// 解析YAML
config := &Config{}
if err := yaml.Unmarshal(data, config); err != nil {
return nil, fmt.Errorf("解析配置文件失败: %w", err)
}
// 设置默认值
if config.API.BaseURL == "" {
config.API.BaseURL = "https://mail.evnmail.com/api"
}
if config.User.DefaultDomain == "" {
config.User.DefaultDomain = "evnmail.com"
}
if config.User.DefaultPassword == "" {
config.User.DefaultPassword = "123456"
}
if config.User.DefaultQuota == 0 {
config.User.DefaultQuota = 1073741824 // 1GB
}
fmt.Printf("已从 %s 加载配置\n", path)
return config, nil
}
// DisableProxy 禁用代理设置
func DisableProxy() {
os.Setenv("HTTP_PROXY", "")
os.Setenv("HTTPS_PROXY", "")
os.Setenv("http_proxy", "")
os.Setenv("https_proxy", "")
}