103 lines
2.1 KiB
Go
103 lines
2.1 KiB
Go
/*
|
|
@Time : 2020/6/28 21:48
|
|
@Author : xuyiqing
|
|
@File : config.py
|
|
*/
|
|
|
|
package conf
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/fsnotify/fsnotify"
|
|
"github.com/go-ini/ini"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type SqlDataBase struct {
|
|
Type string
|
|
Host string
|
|
Port string
|
|
User string
|
|
Password string
|
|
DBName string
|
|
Charset string
|
|
Prefix string
|
|
}
|
|
|
|
type Jwt struct {
|
|
SecretKey string
|
|
}
|
|
|
|
type Project struct {
|
|
StaticUrlMapPath string
|
|
TemplateGlob string
|
|
MediaFilePath string
|
|
}
|
|
|
|
type Server struct {
|
|
Port string
|
|
ReadTimeout time.Duration
|
|
WriteTimeout time.Duration
|
|
}
|
|
|
|
var (
|
|
DataBase = &SqlDataBase{}
|
|
JwtSecretKey = &Jwt{}
|
|
ProjectCfg = &Project{}
|
|
HttpServer = &Server{}
|
|
)
|
|
|
|
func SetUp() {
|
|
cfg, err := ini.Load("conf/conf.ini")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if err := cfg.Section("mysql").MapTo(DataBase); err != nil {
|
|
panic(err)
|
|
}
|
|
if err := cfg.Section("jwt").MapTo(JwtSecretKey); err != nil {
|
|
panic(err)
|
|
}
|
|
if err := cfg.Section("project").MapTo(ProjectCfg); err != nil {
|
|
panic(err)
|
|
}
|
|
if err := cfg.Section("server").MapTo(HttpServer); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func SetUp1() {
|
|
// 设置配置文件的名称(不包括扩展名)
|
|
viper.SetConfigName("config.yml")
|
|
// 设置配置文件所在的目录
|
|
viper.AddConfigPath("./conf")
|
|
// 设置配置文件的类型为YAML
|
|
viper.SetConfigType("yaml")
|
|
|
|
// 读取配置文件
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
log.Fatalf("Error reading config file, %s", err)
|
|
}
|
|
|
|
viper.WatchConfig()
|
|
viper.OnConfigChange(func(e fsnotify.Event) {
|
|
// 配置文件发生变更之后会调用的回调函数
|
|
fmt.Println("Config file changed:", e.Name)
|
|
})
|
|
|
|
// 获取配置值
|
|
mysqlHost := viper.GetString("mysql.Host")
|
|
jwtSecretKey := viper.GetString("jwt.SecretKey")
|
|
serverPort := viper.GetInt("server.Port")
|
|
|
|
templateGlob := viper.GetString("project.TemplateGlob")
|
|
// 打印获取到的配置值
|
|
fmt.Printf("MySQL Host: %s\n", mysqlHost)
|
|
fmt.Printf("JWT Secret Key: %s\n", jwtSecretKey)
|
|
fmt.Printf("Server Port: %d\n", serverPort)
|
|
fmt.Printf("TemplateGlob: %s\n", templateGlob)
|
|
}
|