78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"os"
|
||
|
|
||
|
"github.com/spf13/viper"
|
||
|
)
|
||
|
|
||
|
type Config struct {
|
||
|
Server ServerConfig
|
||
|
Database DatabaseConfig
|
||
|
JWT JWTConfig
|
||
|
Email EmailConfig
|
||
|
Upload UploadConfig
|
||
|
Site SiteConfig
|
||
|
}
|
||
|
|
||
|
type ServerConfig struct {
|
||
|
Port string
|
||
|
Mode string
|
||
|
}
|
||
|
|
||
|
type DatabaseConfig struct {
|
||
|
Type string
|
||
|
Path string
|
||
|
}
|
||
|
|
||
|
type JWTConfig struct {
|
||
|
Secret string
|
||
|
Expire string
|
||
|
}
|
||
|
|
||
|
type EmailConfig struct {
|
||
|
Host string
|
||
|
Port int
|
||
|
Username string
|
||
|
Password string
|
||
|
}
|
||
|
|
||
|
type UploadConfig struct {
|
||
|
Path string
|
||
|
}
|
||
|
|
||
|
type SiteConfig struct {
|
||
|
Title string `mapstructure:"title"`
|
||
|
Description string `mapstructure:"description"`
|
||
|
BaseURL string `mapstructure:"base_url"`
|
||
|
ICP string `mapstructure:"icp"`
|
||
|
Copyright string `mapstructure:"copyright"`
|
||
|
Logo string `mapstructure:"logo"`
|
||
|
Favicon string `mapstructure:"favicon"`
|
||
|
}
|
||
|
|
||
|
func LoadConfig() (*Config, error) {
|
||
|
viper.SetConfigName("config")
|
||
|
viper.SetConfigType("yaml")
|
||
|
viper.AddConfigPath("./config")
|
||
|
|
||
|
// 读取环境变量
|
||
|
viper.AutomaticEnv()
|
||
|
|
||
|
if err := viper.ReadInConfig(); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
config := &Config{}
|
||
|
if err := viper.Unmarshal(config); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
// 环境变量优先
|
||
|
if port := os.Getenv("SERVER_PORT"); port != "" {
|
||
|
config.Server.Port = port
|
||
|
}
|
||
|
|
||
|
return config, nil
|
||
|
}
|