小工具知识网

当前位置: 首页 > 行业知识 > 【go语言开发】yaml文件配置和解析

行业知识

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

2026-11-15 16:46:31 来源:互联网转载

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

文章目录

  • 安装yaml依赖库
  • 配置yaml文件
  • 解析yaml文件

    欢迎大家访问个人博客网址: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: trueredis:  host: localhost  port: 6379  password: ""  db: 0 #数据库编号log:  # 通道数据大小  chan-size: 30  # 每三条保存数据一次  save-log-num: 3

    解析yaml文件

    package coreimport ("fmt""gopkg.in/yaml.v3""os")var Config YamlConfigtype 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 configfunc 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

    终端打印:

上一篇:服务器登录界面在哪里?

下一篇:2024年前端最新记一次字节跳动前端面试,四轮技术面通过,已拿offer(2),正式加入阿里巴巴