go加载配置

go 复制代码
package config

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"log"
	"os"
	"strings"
)

const (
	configFilePattern    = "config/%s"
	mainConfigFile       = "application.yaml"
	addConfigFilePattern = "application-%s.yaml"
)

// LoadConfig 加载配置信息
// 参数 cfg 为待赋值配置对象引用
// 加载"config/application.yaml和config/application-[ENV]"配置文件,其中"ENV"可以是英文逗号分割字符串,加载顺序由前往后,优先级由低到高(即相同配置后面覆盖前面)
func LoadConfig(cfg interface{}) error {
	env := strings.TrimSpace(os.Getenv("ENV"))
	configFileNames := []string{mainConfigFile}
	if len(env) != 0 {
		profiles := strings.Split(env, ",")
		for i := 0; i < len(profiles); i++ {
			profile := strings.TrimSpace(profiles[i])
			if len(profile) == 0 {
				continue
			}
			configFileNames = append(configFileNames, fmt.Sprintf(addConfigFilePattern, profile))
		}
	}
	for _, configFileName := range configFileNames {
		filePath := fmt.Sprintf(configFilePattern, configFileName)
		if _, err := os.Stat(filePath); os.IsNotExist(err) {
			log.Println(fmt.Sprintf("配置文件 %s 不存在,已跳过加载", filePath))
			continue
		}
		yamlFile, err := os.ReadFile(filePath)
		if err != nil {
			log.Println(fmt.Sprintf("配置文件 %s 加载异常:%v", filePath, err))
			return err
		}
		err = yaml.Unmarshal(yamlFile, cfg)
		if err != nil {
			fmt.Errorf("配置文件 %s 解析异常: %v", filePath, err)
			return err
		}
	}
	return nil
}

配置

go 复制代码
package config

import (
	"github.com/redis/go-redis/v9"
)

// ServerConfig Web服务配置
type ServerConfig struct {
	Port int    `yaml:"port"`
	Name string `yaml:"name"`
}

// DatasourceConfig 数据源配置
type DatasourceConfig struct {
	Host            string `yaml:"host"`
	Port            int    `yaml:"port"`
	Username        string `yaml:"username"`
	Password        string `yaml:"password"`
	DatabaseName    string `yaml:"databaseName"`
	MaxIdleConns    int    `yaml:"maxIdleConns"`    // 设置最大空闲连接数
	MaxOpenConns    int    `yaml:"maxOpenConns"`    // 设置最大空闲连接数
	ConnMaxLifetime int    `yaml:"connMaxLifetime"` // 设置连接的最大生命周期
}

// RedisConfig Redis配置
type RedisConfig struct {
	Host            string `yaml:"host"`
	Port            int    `yaml:"port"`
	Password        string `yaml:"password"`
	Database        int    `yaml:"database"`
	PoolSize        int    `yaml:"poolSize"`        // 连接池大小
	MaxIdleConns    int    `yaml:"maxIdleConns"`    // 最大空闲连接
	ConnMaxLifetime int    `yaml:"connMaxLifetime"` // 设置连接的最大生命周期
}

// BusConfig Redis配置
type BusConfig struct {
}

type Config struct {
	ServerConfig     `yaml:"server"`
	DatasourceConfig `yaml:"datasource"`
	RedisConfig      redis.Options `yaml:"redis"`

	BusConfig `yaml:"bus"`
}

加载

go 复制代码
appConfig := config.Config{}
globalConfigs.LoadConfig(&appConfig)
相关推荐
2301_763472467 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
TechWJ7 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
Coder_Boy_8 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
lly2024068 小时前
C++ 文件和流
开发语言
m0_706653238 小时前
分布式系统安全通信
开发语言·c++·算法
2501_941982058 小时前
深度对比:Java、Go、Python 实现企微外部群推送,哪个效率更高?
java·golang·企业微信
寻寻觅觅☆8 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
lightqjx9 小时前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
掘金者阿豪9 小时前
关系数据库迁移的“暗礁”:金仓数据库如何规避数据完整性与一致性风险
后端
zh_xuan9 小时前
kotlin lazy委托异常时执行流程
开发语言·kotlin