侧边栏壁纸
博主头像
猫哥说博主等级

只要付出足够多的时间和耐心,随机过程总会收敛到和付出相对的稳态。

  • 累计撰写 10 篇文章
  • 累计创建 6 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
go

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

Administrator
2024-03-05 / 0 评论 / 0 点赞 / 188 阅读 / 7251 字

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

@[TOC]

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

安装yaml依赖库

命令行执行如下命令:

go get gopkg.in/yaml.v3

配置yaml文件

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

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文件

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

终端打印:
yaml文件配置打印.png

0

评论区