113 lines
2.4 KiB
Go
113 lines
2.4 KiB
Go
package config
|
|
|
|
import (
|
|
"busniess-user-center/pkg/log"
|
|
"bytes"
|
|
"strconv"
|
|
|
|
"dario.cat/mergo"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type RunEnv string
|
|
|
|
const (
|
|
RunEnvDev RunEnv = "dev"
|
|
RunEnvTest RunEnv = "test"
|
|
RunEnvBeta RunEnv = "beta"
|
|
RunEnvProd RunEnv = "prod"
|
|
)
|
|
|
|
type Mysql struct {
|
|
Database string `mapstructure:"database" json:"database"`
|
|
Host string `mapstructure:"host" json:"host"`
|
|
Port int `mapstructure:"port" json:"port"`
|
|
Password string `mapstructure:"password" json:"password"`
|
|
User string `mapstructure:"user" json:"user"`
|
|
|
|
MaxIdleConns int `mapstructure:"max_idle_conns" json:"max_idle_conns"`
|
|
MaxOpenConns int `mapstructure:"max_open_conns" json:"max_open_conns"`
|
|
|
|
ProjectMaxIdleConns int `mapstructure:"project_max_idle_conns" json:"project_max_idle_conns"`
|
|
ProjectMaxOpenConns int `mapstructure:"project_max_open_conns" json:"project_max_open_conns"`
|
|
}
|
|
|
|
type App struct {
|
|
RunEnv RunEnv `mapstructure:"run_env"`
|
|
Name string `mapstructure:"name"`
|
|
Code string `mapstructure:"code"`
|
|
Host string `mapstructure:"host"`
|
|
Port int `mapstructure:"port"`
|
|
}
|
|
|
|
type Jwt struct {
|
|
Secret string `mapstructure:"secret"`
|
|
Expires int `mapstructure:"expires"`
|
|
}
|
|
|
|
type AppConfig struct {
|
|
App App `mapstructure:"app"`
|
|
Jwt Jwt `mapstructure:"app"`
|
|
Log log.Conf `mapstructure:"log"`
|
|
Mysql Mysql `mapstructure:"mysql"`
|
|
}
|
|
|
|
func LoadConfig(fPath string) (*AppConfig, error) {
|
|
viper.SetConfigFile(fPath)
|
|
viper.SetConfigType("yaml")
|
|
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
config := AppConfig{}
|
|
if err := viper.Unmarshal(&config); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
defaultConfig := defaultConfig()
|
|
if err := mergo.Merge(&config, defaultConfig); err != nil {
|
|
return nil, err
|
|
}
|
|
return &config, nil
|
|
}
|
|
|
|
func defaultConfig() *AppConfig {
|
|
return &AppConfig{
|
|
App: App{
|
|
Name: "test",
|
|
Code: "test",
|
|
Host: "test",
|
|
Port: 9001,
|
|
},
|
|
Jwt: Jwt{
|
|
Expires: 7100,
|
|
Secret: "test",
|
|
},
|
|
}
|
|
}
|
|
|
|
func (m *Mysql) TransDns() string {
|
|
buf := bytes.Buffer{}
|
|
|
|
buf.WriteString(m.User)
|
|
buf.WriteString(":")
|
|
buf.WriteString(m.Password)
|
|
buf.WriteString("@tcp(")
|
|
|
|
buf.WriteString(m.Host)
|
|
buf.WriteString(":")
|
|
buf.WriteString(strconv.Itoa(m.Port))
|
|
buf.WriteString(")/")
|
|
|
|
if m.Database != "" {
|
|
buf.WriteString(m.Database)
|
|
}
|
|
|
|
buf.WriteString("?parseTime=true")
|
|
buf.WriteString("&loc=Local")
|
|
|
|
buf.WriteString("&timeout=3s") //设置连接超时时间
|
|
return buf.String()
|
|
}
|