config.go 1.87 KB
Newer Older
qiuqunfeng's avatar
qiuqunfeng committed
1 2 3
package app

import (
4
	"encoding/json"
qiuqunfeng's avatar
qiuqunfeng committed
5 6
	"os"

qiuqunfeng's avatar
qiuqunfeng committed
7
	"github.com/rs/zerolog/log"
qiuqunfeng's avatar
qiuqunfeng committed
8 9
)

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 {
19 20 21 22
	DBConfig      *DBConfig      `json:"db_config"`
	RegionConfigs []RegionConfig `json:"region_configs"`
	Debug         bool           `json:"debug"`
	GatewayUrl    string         `json:"gateway_url"`
23
	SSOUrl        string         `json:"sso_url"`
qiuqunfeng's avatar
config  
qiuqunfeng committed
24 25 26
}

type DBConfig struct {
27 28 29 30 31
	User     string `json:"user"`
	Password string `json:"password"`
	Host     string `json:"host"`
	Port     string `json:"port"`
	Database string `json:"database"`
qiuqunfeng's avatar
qiuqunfeng committed
32 33 34
}

type RegionConfig struct {
35 36 37 38 39 40 41
	RegionCode     string `json:"region_code"`
	ApiServer      string `json:"api_server"`
	CAData         string `json:"ca_data"`
	Token          string `json:"token"`
	ClientCertData string `json:"client_cert_data"`
	ClientKeyData  string `json:"client_key_data"`
	Insecure       bool   `json:"insecure"`
qiuqunfeng's avatar
qiuqunfeng committed
42 43 44
}

func LoadConfig() *Config {
45
	configFile := "config/config.json"
qiuqunfeng's avatar
qiuqunfeng committed
46 47 48 49 50 51
	if envFile := os.Getenv("CONFIG_FILE"); envFile != "" {
		configFile = envFile
	}

	data, err := os.ReadFile(configFile)
	if err != nil {
qiuqunfeng's avatar
qiuqunfeng committed
52
		log.Err(err).Msgf("Failed to read config file: %s", configFile)
qiuqunfeng's avatar
qiuqunfeng committed
53 54 55 56
		return nil
	}

	var config Config
57 58 59 60 61
	// if err := yaml.Unmarshal(data, &config); err != nil {
	// 	log.Err(err).Msg("Failed to parse config file")
	// 	return nil
	// }
	if err := json.Unmarshal(data, &config); err != nil {
qiuqunfeng's avatar
qiuqunfeng committed
62
		log.Err(err).Msg("Failed to parse config file")
qiuqunfeng's avatar
qiuqunfeng committed
63 64
		return nil
	}
65 66 67 68
	password := os.Getenv("RDB_PASSWORD")
	if password != "" {
		config.DBConfig.Password = password
	}
qiuqunfeng's avatar
config  
qiuqunfeng committed
69 70 71 72 73 74 75 76 77 78
	// 如果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
79 80 81

	return &config
}