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)
相关推荐
y = xⁿ几秒前
关于Agent智能体开发
开发语言·前端·javascript
Zhou1411362 分钟前
MyBatisPlus_02_条件构造器与高级功能
java·开发语言·python
geovindu3 分钟前
rust: search
开发语言·后端·rust
the局外人6 分钟前
读懂LangGraph 的分支执行逻辑
后端·langchain·llm
SimonKing10 分钟前
Stream-Nexus:我的轻量级推送中间件(sse、websocket)终于定下来了
java·后端·程序员
重生之小比特22 分钟前
【C++进阶】封装红⿊树实现mymap和myset
开发语言·c++
打工仔折腾 AI23 分钟前
网易UU远程实测:手机控电脑做Python开发和Agent调试的真实体验
人工智能·后端·python·智能手机·性能优化·电脑·ai agent 实战
边境悍匪26 分钟前
蜗牛学苑 Java 智能体学习 Day49|贯穿项目 5 订单下单业务 思维导图复盘
java·开发语言·spring boot·学习·阿里云
“AI国潮设计-小江”30 分钟前
【AIGC实战】Python+SDXL打造潮汕国潮IP:英歌舞麻将的自动化生成与商用思路
开发语言·人工智能·python·prompt·aigc
GoFly开发者33 分钟前
纯 Go 桌面 AI 智能体实战:Wails3 + Eino ADK 构建 Agent 对话应用(流式输出 / 工具审批 / RAG / 打包全记录)
golang·ai agent·eino·wails3·agent桌面开发