【go语言开发】yaml文件配置和解析

本文主要介绍使用第三方库来对yaml文件配置和解析。首先安装yaml依赖库;然后yaml文件中配置各项值,并给出demo参考;最后解析yaml文件,由于yaml文件的配置在全局中可能需要,可定义全局变量Config,便于调用

文章目录

欢迎大家访问个人博客网址:https://www.maogeshuo.com,博主努力更新中...

安装yaml依赖库

命令行执行如下命令:

go 复制代码
go get gopkg.in/yaml.v3

配置yaml文件

在config-dev.yaml 文件中配置所需key-value,参考如下文件配置

go 复制代码
app:
  name: code-go
  version: v0.0.1
  introduction: "code-go是一个学习go的项目~"
server:
  host: localhost
  port: 8080
  appMode: debug # debug  开发模式   release  生产模式

database:
  mysql:
    # 用户名
    username: root
    # 密码
    password: 123456
    # 数据库名
    database: code-go
    # 主机地址
    host: localhost
    # 端口
    port: 3306
    # 是否开启日志
    log-mode: true

redis:
  host: localhost
  port: 6379
  password: ""
  db: 0 #数据库编号

log:
  # 通道数据大小
  chan-size: 30
  # 每三条保存数据一次
  save-log-num: 3

解析yaml文件

go 复制代码
package core

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

var Config YamlConfig

type YamlConfig struct {
	App      App            `yaml:"app"`
	Server   ServerConfig   `yaml:"server"`
	Database DatabaseConfig `yaml:"database"`
	Redis    RedisConfig    `yaml:"redis"`
	Log      LogConfig      `yaml:"log"`
}

type App struct {
	Name         string `yaml:"name"`
	Version      string `yaml:"version"`
	Introduction string `yaml:"introduction"`
}

type ServerConfig struct {
	Host    string `yaml:"host"`
	Port    int    `yaml:"port"`
	AppMode string `yaml:"appMode"`
}

type DatabaseConfig struct {
	Mysql MysqlConfig `yaml:"mysql"`
}

type MysqlConfig struct {
	UserName string `yaml:"username"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	LogMode  bool   `yaml:"log-mode"`
}

type RedisConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Password string `yaml:"password"`
	Db       int    `yaml:"db"`
}

type LogConfig struct {
	ChanSize   int `yaml:"chan-size"`
	SaveLogNum int `yaml:"save-log-num"`
}

// InitConfigDev 初始化yaml config
func InitConfigDev() error {
	file, err := os.ReadFile("./config-dev.yaml")
	if err != nil {
		LOG.Println("read config-dev.yaml fail", err)
		return err
	}

	err = yaml.Unmarshal(file, &Config)
	if err != nil {
		LOG.Println("yaml unmarshal fail")
		return err
	}
	return nil
}

// PrintConfig 打印配置
func PrintConfig() {
	fmt.Println("**************************************************")
	fmt.Println("*                        ")
	fmt.Println("*   Welcome to code-go   ")
	fmt.Printf("*   Introduction: %s\n", Config.App.Introduction)
	fmt.Printf("*   Environment: %s\n", Config.Server.AppMode)
	fmt.Printf("*   Click url:http://localhost:%d\n", Config.Server.Port)
	fmt.Printf("*   Swagger url: http://localhost:%d/swagger/index.html\n", Config.Server.Port)
	fmt.Println("*                        ")
	fmt.Println("**************************************************")
}

定义了一个YamlConfig结构体,并在结构体中嵌套了App、ServerConfig等结构体,以对应YAML文件中的不同层级。

通过使用.ReadFile函数读取YAML文件的内容,然后使用yaml.Unmarshal函数将文件内容解析为结构体对象。在Unmarshal函数的第二个参数中,传入了指向config结构体的指针,以便将解析后的内容赋值给结构体。

最后,我们可以通过PrintConfig访问结构体的字段来获取解析后的配置信息,并进行相应的操作。

注意:

博主将config-dev.yaml 放在项目根目录下,因此调用os.ReadFile 配置的./config-dev.yaml

终端打印:

相关推荐
朝朝辞暮i4 小时前
C++ 第 23 课:class —— 开始真正进入面向对象
开发语言·c++·算法
明月_清风5 小时前
Muse 登顶 App Store 第一,SDK 直接开源:AI Agent 开始进入下一个阶段
人工智能·后端
小师兄吃牛肉5 小时前
C语言篇:宏
c语言·开发语言
郑同学的笔记5 小时前
【c++随笔28】strcmp 和 memcmp对比
开发语言·c++
言乐66 小时前
Python根据无法识别搜索词找出可能输入内容模型
开发语言·python·django·virtualenv·pygame
weixin_307779136 小时前
有限产能智能排产与动态重排智能体:从需求解构到技术实现
开发语言·人工智能·算法·架构
kakakahahahaha6 小时前
Windows C盘临时文件清理:%temp%、Windows Temp、Prefetch、Windows.old与hiberfil.sys处理指南
c语言·开发语言·windows
朝朝辞暮i6 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法
朝朝辞暮i7 小时前
C++ 第 29 课:回调函数 Callback
开发语言·c++·算法
笨笨饿7 小时前
140_AI新手村MCP与Skills是干嘛的
开发语言·人工智能·python·stm32·单片机·嵌入式硬件·物联网