You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.3 KiB
71 lines
1.3 KiB
package config |
|
|
|
import ( |
|
"fmt" |
|
|
|
"github.com/spf13/viper" |
|
) |
|
|
|
type Config struct { |
|
DB DBConfig |
|
Server ServerConfig |
|
Redis RedisConfig |
|
JWT JWTConfig |
|
Log LogConfig // 新增日志配置 |
|
} |
|
|
|
type DBConfig struct { |
|
Host string |
|
Port string |
|
User string |
|
Password string |
|
Name string |
|
} |
|
|
|
type ServerConfig struct { |
|
Port string |
|
} |
|
|
|
type RedisConfig struct { |
|
Host string |
|
Port string |
|
Password string |
|
DB int |
|
} |
|
|
|
type JWTConfig struct { |
|
Secret string |
|
Issuer string |
|
Expire int // 小时 |
|
} |
|
|
|
// 新增日志配置结构 |
|
type LogConfig struct { |
|
Level string // 日志级别: debug, info, warn, error |
|
Path string // 日志文件路径 |
|
} |
|
|
|
func LoadConfig() (*Config, error) { |
|
viper.SetConfigName("config") |
|
viper.SetConfigType("yaml") |
|
viper.AddConfigPath(".") |
|
viper.AutomaticEnv() |
|
|
|
// 设置默认值 |
|
viper.SetDefault("jwt.secret", "your-secret-key") |
|
viper.SetDefault("jwt.issuer", "gofaster") |
|
viper.SetDefault("jwt.expire", 24) |
|
|
|
if err := viper.ReadInConfig(); err != nil { |
|
return nil, fmt.Errorf("error reading config file: %w", err) |
|
} |
|
|
|
var cfg Config |
|
if err := viper.Unmarshal(&cfg); err != nil { |
|
return nil, fmt.Errorf("unable to decode into struct: %w", err) |
|
} |
|
|
|
fmt.Println("Configuration loaded successfully") |
|
|
|
return &cfg, nil |
|
}
|
|
|