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.
68 lines
1.7 KiB
68 lines
1.7 KiB
package config
|
|
|
|
import (
|
|
"log"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type Config struct {
|
|
Server ServerConfig `mapstructure:"server"`
|
|
Database DatabaseConfig `mapstructure:"database"`
|
|
JWT JWTConfig `mapstructure:"jwt"`
|
|
Log LogConfig `mapstructure:"log"`
|
|
}
|
|
|
|
type ServerConfig struct {
|
|
Port string `mapstructure:"port"`
|
|
Mode string `mapstructure:"mode"`
|
|
}
|
|
|
|
type DatabaseConfig struct {
|
|
Driver string `mapstructure:"driver"`
|
|
Host string `mapstructure:"host"`
|
|
Port string `mapstructure:"port"`
|
|
Username string `mapstructure:"username"`
|
|
Password string `mapstructure:"password"`
|
|
Database string `mapstructure:"database"`
|
|
Charset string `mapstructure:"charset"`
|
|
}
|
|
|
|
type JWTConfig struct {
|
|
Secret string `mapstructure:"secret"`
|
|
Expire int `mapstructure:"expire"`
|
|
}
|
|
|
|
type LogConfig struct {
|
|
Level string `mapstructure:"level"`
|
|
}
|
|
|
|
func Load() *Config {
|
|
viper.SetConfigName("config")
|
|
viper.SetConfigType("yaml")
|
|
viper.AddConfigPath("./config")
|
|
viper.AddConfigPath(".")
|
|
|
|
// 设置默认值
|
|
viper.SetDefault("server.port", "8080")
|
|
viper.SetDefault("server.mode", "debug")
|
|
viper.SetDefault("database.driver", "mysql")
|
|
viper.SetDefault("database.host", "localhost")
|
|
viper.SetDefault("database.port", "3306")
|
|
viper.SetDefault("database.charset", "utf8mb4")
|
|
viper.SetDefault("jwt.secret", "task-track-secret")
|
|
viper.SetDefault("jwt.expire", 24)
|
|
viper.SetDefault("log.level", "info")
|
|
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
log.Printf("Warning: Could not read config file: %v", err)
|
|
log.Println("Using default configuration")
|
|
}
|
|
|
|
var config Config
|
|
if err := viper.Unmarshal(&config); err != nil {
|
|
log.Fatal("Failed to unmarshal config:", err)
|
|
}
|
|
|
|
return &config
|
|
}
|
|
|