config.go 1.55 KB
Newer Older
qiuqunfeng's avatar
qiuqunfeng committed
1 2 3 4 5 6 7 8 9
package app

import (
	"os"

	"gitlab.com/security-rd/go-pkg/logging"
	"gopkg.in/yaml.v2"
)

qiuqunfeng's avatar
config  
qiuqunfeng committed
10 11 12 13 14 15 16 17
const (
	DB_USER     = "ivan"
	DB_PASSWORD = "Mysql-ha@123"
	DB_HOST     = "localhost"
	DB_PORT     = "3306"
	DB_NAME     = "waf"
)

qiuqunfeng's avatar
qiuqunfeng committed
18
type Config struct {
qiuqunfeng's avatar
config  
qiuqunfeng committed
19
	DBConfig      *DBConfig      `yaml:"db_config"`
qiuqunfeng's avatar
qiuqunfeng committed
20
	RegionConfigs []RegionConfig `yaml:"region_configs"`
qiuqunfeng's avatar
config  
qiuqunfeng committed
21 22 23 24 25 26 27 28 29
	Debug         bool           `yaml:"debug"`
}

type DBConfig struct {
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	Database string `yaml:"database"`
qiuqunfeng's avatar
qiuqunfeng committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
}

type RegionConfig struct {
	RegionCode     string `yaml:"region_code"`
	ApiServer      string `yaml:"api_server"`
	CAData         string `yaml:"ca_data"`
	Token          string `yaml:"token"`
	ClientCertData string `yaml:"client_cert_data"`
	ClientKeyData  string `yaml:"client_key_data"`
}

func LoadConfig() *Config {
	configFile := "config.yaml"
	if envFile := os.Getenv("CONFIG_FILE"); envFile != "" {
		configFile = envFile
	}

	data, err := os.ReadFile(configFile)
	if err != nil {
		logging.Get().Error().Err(err).Msgf("Failed to read config file: %s", configFile)
		return nil
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		logging.Get().Error().Err(err).Msg("Failed to parse config file")
		return nil
	}
qiuqunfeng's avatar
config  
qiuqunfeng committed
58 59 60 61 62 63 64 65 66 67
	// 如果config.DBConfig为nil,则使用默认值
	if config.DBConfig == nil {
		config.DBConfig = &DBConfig{
			User:     DB_USER,
			Password: DB_PASSWORD,
			Host:     DB_HOST,
			Port:     DB_PORT,
			Database: DB_NAME,
		}
	}
qiuqunfeng's avatar
qiuqunfeng committed
68 69 70

	return &config
}