Files
workspace/code/base-project/base-go-v3/conf/conf.go
T
2025-11-29 17:23:27 +08:00

96 lines
2.7 KiB
Go

package conf
import (
"github.com/spf13/viper"
"os"
"path/filepath"
"sync"
"time"
)
var (
conf *Config
once sync.Once
)
type Config struct {
Env string
Server ServerConfig `mapstructure:"server" yaml:"server"`
JWT JwtConfig `mapstructure:"jwt" yaml:"jwt"`
Snowflake SnowflakeConfig `mapstructure:"snowflake" yaml:"snowflake"`
Pgsql PgsqlConfig `mapstructure:"pgsql" yaml:"pgsql"`
Log LogConfig `mapstructure:"log" yaml:"log"`
}
type ServerConfig struct {
Port string `mapstructure:"port" yaml:"port"`
BaseUrl string `mapstructure:"base_url" yaml:"base_url"` // 下划线
}
type JwtConfig struct {
Secret string `mapstructure:"secret" yaml:"secret"`
AccessExpiry time.Duration `mapstructure:"access_expiry" yaml:"access_expiry"`
RefreshExpiry time.Duration `mapstructure:"refresh_expiry" yaml:"refresh_expiry"`
}
type SnowflakeConfig struct {
DatacenterID uint16 `mapstructure:"datacenter_id" yaml:"datacenter_id"`
WorkerID uint16 `mapstructure:"worker_id" yaml:"worker_id"`
}
type PgsqlConfig struct {
Host string `mapstructure:"host" yaml:"host"`
Port int `mapstructure:"port" yaml:"port"`
User string `mapstructure:"user" yaml:"user"`
Password string `mapstructure:"password" yaml:"password"`
Dbname string `mapstructure:"dbname" yaml:"dbname"`
SllMode bool `mapstructure:"sll_mode" yaml:"sll_mode"`
TimeZone string `mapstructure:"timezone" yaml:"timezone"`
MaxOpenConns int32 `mapstructure:"max_open_conns" yaml:"max_open_conns"`
MaxIdleConns int32 `mapstructure:"max_idle_conns" yaml:"max_idle_conns"`
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime" yaml:"conn_max_lifetime"`
}
type LogConfig struct {
Level string `mapstructure:"level" yaml:"level"`
Dir string `mapstructure:"dir" yaml:"dir"`
MaxSize int `mapstructure:"max_size" yaml:"max_size"`
MaxBackups int `mapstructure:"max_backups" yaml:"max_backups"`
MaxAge int `mapstructure:"max_age" yaml:"max_age"`
Compress bool `mapstructure:"compress" yaml:"compress"`
}
func GetConf() *Config {
once.Do(initConf)
return conf
}
func initConf() {
prefix := "conf"
confFileRelPath := filepath.Join(prefix, filepath.Join(GetEnv(), "conf.yaml"))
v := viper.New()
v.SetConfigFile(confFileRelPath)
v.SetConfigType("yaml")
if err := v.ReadInConfig(); err != nil {
panic(err)
}
conf = new(Config)
if err := v.Unmarshal(conf); err != nil {
panic(err)
}
conf.Env = GetEnv()
}
func GetEnv() string {
e := os.Getenv("GO_ENV")
if len(e) == 0 {
return "dev"
}
return e
}