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)
相关推荐
.生产的驴几秒前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
wjs20244 分钟前
Chrome 浏览器:现代网络浏览的先锋
开发语言
爱学的小涛8 分钟前
【NIO基础】基于 NIO 中的组件实现对文件的操作(文件编程),FileChannel 详解
java·开发语言·笔记·后端·nio
吹老师个人app编程教学9 分钟前
详解Java中的BIO、NIO、AIO
java·开发语言·nio
爱学的小涛10 分钟前
【NIO基础】NIO(非阻塞 I/O)和 IO(传统 I/O)的区别,以及 NIO 的三大组件详解
java·开发语言·笔记·后端·nio
北极无雪14 分钟前
Spring源码学习:SpringMVC(4)DispatcherServlet请求入口分析
java·开发语言·后端·学习·spring
爱码少年20 分钟前
springboot工程中使用tcp协议
spring boot·后端·tcp/ip
AI视觉网奇37 分钟前
pymeshlab 学习笔记
开发语言·python
木向1 小时前
leetcode42:接雨水
开发语言·c++·算法·leetcode
gopher95111 小时前
final,finally,finalize的区别
java·开发语言·jvm