94 lines
2.9 KiB
Go
94 lines
2.9 KiB
Go
// Package config 负责加载和管理应用程序配置
|
||
// 从 config.yaml 文件中读取配置,并提供全局访问接口
|
||
package config
|
||
|
||
import (
|
||
"os"
|
||
|
||
"gopkg.in/yaml.v2"
|
||
)
|
||
|
||
// Config 应用程序全局配置结构体
|
||
type Config struct {
|
||
Server ServerConfig `yaml:"server"` // 服务器配置
|
||
Database DatabaseConfig `yaml:"database"` // 数据库配置
|
||
Storage StorageConfig `yaml:"storage"` // 文件存储配置
|
||
}
|
||
|
||
// ServerConfig 服务器配置
|
||
type ServerConfig struct {
|
||
Port int `yaml:"port"` // API服务监听端口
|
||
WsPort int `yaml:"ws_port"` // WebSocket服务监听端口
|
||
}
|
||
|
||
// DatabaseConfig 数据库连接配置
|
||
type DatabaseConfig struct {
|
||
Host string `yaml:"host"` // 数据库主机地址
|
||
Port int `yaml:"port"` // 数据库端口
|
||
Username string `yaml:"username"` // 数据库用户名
|
||
Password string `yaml:"password"` // 数据库密码
|
||
DBName string `yaml:"dbname"` // 数据库名称
|
||
Charset string `yaml:"charset"` // 字符集
|
||
}
|
||
|
||
// StorageConfig 文件存储配置
|
||
type StorageConfig struct {
|
||
Type string `yaml:"type"` // 存储类型:local/qiniu/tencent/aliyun
|
||
Local LocalConfig `yaml:"local"` // 本地存储配置
|
||
Qiniu CloudConfig `yaml:"qiniu"` // 七牛云配置
|
||
Tencent CloudConfig `yaml:"tencent"` // 腾讯云配置
|
||
Aliyun CloudConfig `yaml:"aliyun"` // 阿里云配置
|
||
}
|
||
|
||
// LocalConfig 本地存储配置
|
||
type LocalConfig struct {
|
||
Path string `yaml:"path"` // 本地文件存储目录
|
||
}
|
||
|
||
// CloudConfig 云存储通用配置
|
||
type CloudConfig struct {
|
||
AccessKey string `yaml:"access_key"` // 访问密钥ID
|
||
SecretKey string `yaml:"secret_key"` // 访问密钥Secret
|
||
Bucket string `yaml:"bucket"` // 存储桶名称
|
||
Domain string `yaml:"domain"` // 域名(七牛云)
|
||
Region string `yaml:"region"` // 区域(腾讯云)
|
||
SecretID string `yaml:"secret_id"` // SecretID(腾讯云)
|
||
AccessKeyID string `yaml:"access_key_id"` // AccessKeyID(阿里云)
|
||
AccessKeySecret string `yaml:"access_key_secret"` // AccessKeySecret(阿里云)
|
||
Endpoint string `yaml:"endpoint"` // Endpoint(阿里云)
|
||
}
|
||
|
||
// App 全局配置实例
|
||
var App *Config
|
||
|
||
// Init 从 config.yaml 文件加载配置到全局变量 App
|
||
// 如果文件不存在或读取失败,返回错误
|
||
func Init() error {
|
||
App = &Config{}
|
||
data, err := os.ReadFile("config.yaml")
|
||
if err != nil {
|
||
return err
|
||
}
|
||
err = yaml.Unmarshal(data, App)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
// 设置默认值
|
||
if App.Server.Port == 0 {
|
||
App.Server.Port = 16702
|
||
}
|
||
if App.Server.WsPort == 0 {
|
||
App.Server.WsPort = 16703
|
||
}
|
||
if App.Database.Charset == "" {
|
||
App.Database.Charset = "utf8mb4"
|
||
}
|
||
if App.Storage.Type == "" {
|
||
App.Storage.Type = "local"
|
||
}
|
||
if App.Storage.Local.Path == "" {
|
||
App.Storage.Local.Path = "./uploads"
|
||
}
|
||
return nil
|
||
}
|