Files
go_blog/conf/config.go

96 lines
1.9 KiB
Go
Raw Normal View History

2024-01-10 16:05:15 +08:00
/*
@Time : 2020/6/28 21:48
@Author : xuyiqing
@File : config.py
*/
package conf
import (
2024-07-24 04:19:01 +08:00
"fmt"
"log"
2024-01-10 16:05:15 +08:00
"time"
2024-07-04 19:15:44 +08:00
"github.com/go-ini/ini"
2024-07-24 04:19:01 +08:00
"github.com/spf13/viper"
2024-01-10 16:05:15 +08:00
)
type SqlDataBase struct {
Type string
Host string
Port string
User string
Password string
2024-07-04 19:15:44 +08:00
DBName string
2024-01-10 16:05:15 +08:00
Charset string
Prefix string
}
type Jwt struct {
SecretKey string
}
type Project struct {
StaticUrlMapPath string
TemplateGlob string
2024-07-04 19:15:44 +08:00
MediaFilePath string
2024-01-10 16:05:15 +08:00
}
type Server struct {
2024-07-04 19:15:44 +08:00
Port string
ReadTimeout time.Duration
2024-01-10 16:05:15 +08:00
WriteTimeout time.Duration
}
var (
DataBase = &SqlDataBase{}
JwtSecretKey = &Jwt{}
ProjectCfg = &Project{}
2024-07-04 19:15:44 +08:00
HttpServer = &Server{}
2024-01-10 16:05:15 +08:00
)
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)
}
}
2024-07-24 04:19:01 +08:00
func SetUp1() {
// 设置配置文件的名称(不包括扩展名)
2024-08-02 16:25:09 +08:00
viper.SetConfigName("config.yml")
2024-07-24 04:19:01 +08:00
// 设置配置文件所在的目录
2024-08-02 16:25:09 +08:00
viper.AddConfigPath("./conf")
2024-07-24 04:19:01 +08:00
// 设置配置文件的类型为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")
2024-08-01 02:44:06 +08:00
templateGlob := viper.GetString("project.TemplateGlob")
2024-07-24 04:19:01 +08:00
// 打印获取到的配置值
fmt.Printf("MySQL Host: %s\n", mysqlHost)
fmt.Printf("JWT Secret Key: %s\n", jwtSecretKey)
fmt.Printf("Server Port: %d\n", serverPort)
2024-08-01 02:44:06 +08:00
fmt.Printf("TemplateGlob: %s\n", templateGlob)
2024-07-24 04:19:01 +08:00
}