u
This commit is contained in:
1 parent
9e00adf2fe
commit
ae0d245605
34 files changed
+1460
-162
No files matched your search
@@ -0,0 +1,21 @@
|
||||
package config
|
||||
|
||||
type Config struct {
|
||||
App AppConfig `mapstructure:"app"`
|
||||
Postgres PostgresConfig `mapstructure:"postgres"`
|
||||
}
|
||||
|
||||
type AppConfig struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Port int `mapstructure:"port"`
|
||||
}
|
||||
|
||||
type PostgresConfig struct {
|
||||
Host string `mapstructure:"host"`
|
||||
Port int `mapstructure:"port"`
|
||||
User string `mapstructure:"user"`
|
||||
Password string `mapstructure:"password"`
|
||||
Dbname string `mapstructure:"dbname"`
|
||||
SslMode bool `mapstructure:"ssl_mode"`
|
||||
TimeZone string `mapstructure:"timezone"`
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func Load() (*Config, error) {
|
||||
env := getEnv("APP_ENV", "dev")
|
||||
|
||||
v := viper.New()
|
||||
v.SetConfigType("yaml")
|
||||
|
||||
// 基础配置
|
||||
v.AddConfigPath("configs")
|
||||
v.SetConfigName("config")
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
return nil, fmt.Errorf("read base config failed: %w", err)
|
||||
}
|
||||
|
||||
// 环境配置(覆盖)
|
||||
envConfigName := fmt.Sprintf("config.%s", env)
|
||||
v.SetConfigName(envConfigName)
|
||||
|
||||
if err := v.MergeInConfig(); err != nil {
|
||||
// dev 允许没有文件,prod 建议必须存在
|
||||
if env == "prod" {
|
||||
return nil, fmt.Errorf("read env config failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal config failed: %w", err)
|
||||
}
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func getEnv(key, defaultVal string) string {
|
||||
val := os.Getenv(key)
|
||||
if val == "" {
|
||||
return defaultVal
|
||||
}
|
||||
return strings.ToLower(val)
|
||||
}
|
||||
Reference in new issue
Block a user