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)
相关推荐
怕浪猫几秒前
3 小时搭一个能用的聊天机器人后端,我用了这套技术栈
后端·面试·github
星夜离尘5620 分钟前
MATLAB阶跃响应怎么量:别把最后一个采样点当成稳态
开发语言·matlab
云水初33 分钟前
【agent篇】RAG Agent避坑指南(附高级RAG Agent汇总)
开发语言·笔记·python·学习·langchain·agent·rag
Littlehero_12135 分钟前
QT自定义控件之水泥厂组态(源码开源)
开发语言·qt
xiaoqiMikko39 分钟前
Redis 实战(二):宕机会丢多少数据 —— kill -9 与真断电下 RDB / AOF 逐个实测(6.2.4)
redis·后端
辛苦才能44 分钟前
C++ 哈希表深度解析:删除为什么必须打标记,负载因子为什么卡 0.7
开发语言·数据结构·c++·算法
李哈哈8521 小时前
微服务依赖冲突
后端
努力的小雨1 小时前
每天盯着屏幕写代码,我终于不想再凑合了
后端
海岳云舟1 小时前
springboot项目中使用AOP
后端
小稀土1231 小时前
5步跑通第一个迭代:敏捷研发管理平台落地最小闭环
后端