u
This commit is contained in:
1 parent
d04d22723b
commit
4ce951dd56
30 files changed
+982
-74
No files matched your search
@@ -4,6 +4,8 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
@@ -12,11 +14,62 @@ var (
|
||||
conf *Config
|
||||
)
|
||||
|
||||
func InitConf() {
|
||||
func InitConfig() error {
|
||||
// 加载配置
|
||||
err := readConfigFile()
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("read config file failed: %w", err)
|
||||
}
|
||||
|
||||
initLogger()
|
||||
initUniqueId()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func defaultConfig() *Config {
|
||||
return &Config{
|
||||
Server: ServerConfig{
|
||||
Port: "8080",
|
||||
BaseUrl: "/",
|
||||
WsUrl: "/ws",
|
||||
},
|
||||
JWT: JwtConfig{
|
||||
Secret: "qwemwddlalmskadklsdklamlkdsakld",
|
||||
AccessExpiry: 24 * time.Hour,
|
||||
},
|
||||
UniqueID: UniqueIDConfig{
|
||||
DataCenterID: 1,
|
||||
WorkerID: 1,
|
||||
},
|
||||
Postgres: PostgresConfig{
|
||||
Port: 5432,
|
||||
SslMode: false,
|
||||
TimeZone: "Asia/Shanghai",
|
||||
MaxOpenConns: 20,
|
||||
MaxIdleConns: 10,
|
||||
ConnMaxLifetime: 30 * time.Minute,
|
||||
},
|
||||
Log: LogConfig{
|
||||
Level: "info",
|
||||
Dir: "logs",
|
||||
MaxSize: 100,
|
||||
MaxBackups: 10,
|
||||
MaxAge: 30,
|
||||
Compress: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func readConfigFile() error {
|
||||
// 配置文件的目录
|
||||
prefix := "resources"
|
||||
env := GetEnv() // 获取当前环境
|
||||
|
||||
// 设置默认值
|
||||
conf = defaultConfig() // 先给默认结构体
|
||||
|
||||
// 默认配置文件
|
||||
confFileRelPath := filepath.Join(prefix, "application.yaml")
|
||||
|
||||
@@ -42,18 +95,18 @@ func InitConf() {
|
||||
|
||||
// 如果需要,合并环境特定的配置文件
|
||||
if err := v.MergeInConfig(); err != nil {
|
||||
panic(err)
|
||||
return fmt.Errorf("merge env config failed: %w", err)
|
||||
}
|
||||
|
||||
// 将配置文件反序列化到 Config 结构体
|
||||
conf = new(Config)
|
||||
if err := v.Unmarshal(conf); err != nil {
|
||||
panic(err)
|
||||
return fmt.Errorf("unmarshal config failed: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("✅️ 加载配置成功")
|
||||
// 设置环境变量
|
||||
conf.Env = env
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetEnv 获取 GO_ENV 环境变量,默认返回 "dev"
|
||||
@@ -66,6 +119,16 @@ func GetEnv() string {
|
||||
return e
|
||||
}
|
||||
|
||||
// GetConf 获取配置信息
|
||||
func GetConf() *Config {
|
||||
return conf
|
||||
}
|
||||
|
||||
// GetServerPort 项目启动端口
|
||||
func GetServerPort() string {
|
||||
port := conf.Server.Port
|
||||
if strings.HasPrefix(port, ":") {
|
||||
return port
|
||||
}
|
||||
return ":" + port
|
||||
}
|
||||
Reference in new issue
Block a user