Files
go_blog/conf/config.go
2024-08-02 16:25:09 +08:00

94 lines
1.8 KiB
Go

/*
@Time : 2020/6/28 21:48
@Author : xuyiqing
@File : config.py
*/
package conf
import (
"fmt"
"log"
"time"
"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)
}
// 获取配置值
mysqlHost := viper.GetString("mysql.Host")
jwtSecretKey := viper.GetString("jwt.SecretKey")
serverPort := viper.GetInt("server.Port")
// 打印获取到的配置值
fmt.Printf("MySQL Host: %s\n", mysqlHost)
fmt.Printf("JWT Secret Key: %s\n", jwtSecretKey)
fmt.Printf("Server Port: %d\n", serverPort)
}