You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
1.9 KiB
Go
96 lines
1.9 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// Config 应用配置
|
|
type Config struct {
|
|
Gin GinConfig `json:"gin" yaml:"gin"`
|
|
Storage StorageConfig `json:"storage" yaml:"storage"`
|
|
}
|
|
|
|
// GinConfig Gin配置
|
|
type GinConfig struct {
|
|
Port string `json:"port" yaml:"port"`
|
|
}
|
|
|
|
// StorageConfig 存储配置
|
|
type StorageConfig struct {
|
|
Root string `json:"root" yaml:"root"`
|
|
}
|
|
|
|
// getDefaultConfig 获取默认配置
|
|
func getDefaultConfig() *Config {
|
|
return &Config{
|
|
Gin: GinConfig{
|
|
Port: "8850",
|
|
},
|
|
Storage: StorageConfig{
|
|
Root: "D:/aa",
|
|
},
|
|
}
|
|
}
|
|
|
|
// loadFromFile 从配置文件加载配置
|
|
func loadFromFile() (*Config, error) {
|
|
configPaths := []string{
|
|
"./config.yaml",
|
|
}
|
|
|
|
for _, path := range configPaths {
|
|
if _, err := os.Stat(path); err == nil {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read config file error: %w", err)
|
|
}
|
|
|
|
var config Config
|
|
if err := yaml.Unmarshal(data, &config); err != nil {
|
|
return nil, fmt.Errorf("unmarshal config file error: %w", err)
|
|
}
|
|
|
|
return &config, nil
|
|
}
|
|
}
|
|
|
|
return nil, nil
|
|
}
|
|
|
|
// loadFromEnv 从环境变量加载配置
|
|
func loadFromEnv(config *Config) {
|
|
// 加载 Gin 配置
|
|
if port := os.Getenv("GIN_PORT"); port != "" {
|
|
config.Gin.Port = port
|
|
}
|
|
|
|
// 加载 Storage 配置
|
|
if root := os.Getenv("STORAGE_ROOT"); root != "" {
|
|
config.Storage.Root = root
|
|
}
|
|
}
|
|
|
|
// GetConfig 获取配置
|
|
func GetConfig() *Config {
|
|
// 先加载默认配置
|
|
config := getDefaultConfig()
|
|
|
|
// 再从配置文件加载
|
|
if fileConfig, err := loadFromFile(); err == nil && fileConfig != nil {
|
|
// 合并配置文件中的配置
|
|
if fileConfig.Gin.Port != "" {
|
|
config.Gin.Port = fileConfig.Gin.Port
|
|
}
|
|
if fileConfig.Storage.Root != "" {
|
|
config.Storage.Root = fileConfig.Storage.Root
|
|
}
|
|
}
|
|
|
|
// 最后从环境变量加载
|
|
loadFromEnv(config)
|
|
|
|
return config
|
|
} |