在 Go (Golang) 中使用 YAML:go-yaml 和 yaml.v3 库

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 Go (Golang) 中使用 YAML:完整指南



YAML (YAML Ain't Markup Language) 是一种人类可读的数据序列化格式,广泛用于配置文件、基础设施描述(例如 Kubernetes、Docker Compose)以及数据交换。在 Go (Golang) 生态系统中,通过强大的第三方库(主要是 go-yaml,即 gopkg.in/yaml.v3)来实现对 YAML 的支持。在本文中,我们将详细介绍如何在 Go 中解析、创建和处理 YAML 文档。



为什么 YAML 对 Go 开发者很重要?

Go 是一种用于构建高性能服务器应用程序、DevOps 工具和微服务的语言。YAML 已成为以下方面的实际标准:

  • 应用程序配置(例如 config.yaml);
  • Kubernetes 清单文件(deployment.yaml);
  • CI/CD 流水线(GitLab CI、GitHub Actions);
  • API 和数据模式描述。

没有在 Go 中使用 YAML 的能力,就无法想象现代 Go 语言开发。



在 Go 中使用 YAML 的主要库

目前,该库有两个主要版本:

  • gopkg.in/yaml.v2 — 旧的稳定版本,仍然很流行;
  • gopkg.in/yaml.v3 — 当前版本,支持标签、通道和更好的错误处理(推荐用于新项目)。

这两个库都提供 Marshal(结构体 → YAML)和 Unmarshal(YAML → 结构体)函数。



安装库

首先,将包添加到项目中:

go get gopkg.in/yaml.v3

在代码中导入它:

import "gopkg.in/yaml.v3"


示例 1:将 YAML 解析为结构体 (Unmarshal)

创建一个配置文件 config.yaml:

server:  host: "localhost"  port: 8080database:  driver: "postgres"  dsn: "host=localhost user=app password=secret dbname=mydb"logging:  level: "info"  file: "/var/log/app.log"

现在编写 Go 代码来读取此文件:

package main

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

type Config struct { Server ServerConfig `yaml:"server"` Database DatabaseConfig `yaml:"database"` Logging LoggingConfig `yaml:"logging"`}

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

type DatabaseConfig struct { Driver string `yaml:"driver"` DSN string `yaml:"dsn"`}

type LoggingConfig struct { Level string `yaml:"level"` File string `yaml:"file"`}

func main() { data, err := os.ReadFile("config.yaml") if err != nil { panic(err) }

var cfg Config err = yaml.Unmarshal(data, &cfg) if err != nil { panic(err) }

fmt.Printf("Server: %s:%d", cfg.Server.Host, cfg.Server.Port) fmt.Printf("Database driver: %s", cfg.Database.Driver) fmt.Printf("Log level: %s", cfg.Logging.Level)}

输出:

Server: localhost:8080Database driver: postgresLog level: info


示例 2:将结构体序列化为 YAML (Marshal)

现在创建一个结构体并将其转换为 YAML:

package main

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

type AppConfig struct { Name string `yaml:"name"` Version string `yaml:"version"` Debug bool `yaml:"debug"` Tags []string `yaml:"tags"`}

func main() { cfg := AppConfig{ Name: "MyApp", Version: "1.0.0", Debug: false, Tags: []string{"production", "stable"}, }

out, err := yaml.Marshal(&cfg) if err != nil { panic(err) }

fmt.P

推荐