Skip to content

yaml

yaml.v3

sh
go get gopkg.in/yaml.v3
yaml
server:
  host: localhost
  port: 8080

debug: true
timeout: 5s

struct 首字母必须大写

go
package main

import (
	"fmt"
	"os"
	"time"

	"gopkg.in/yaml.v3"
)

type Config struct {
	Server  ServerConfig `yaml:"server"`
	Debug   bool         `yaml:"debug"`
	Timeout time.Duration `yaml:"timeout"`
}

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

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

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

	fmt.Println("Host:", cfg.Server.Host)
	fmt.Println("Port:", cfg.Server.Port)
	fmt.Println("Debug:", cfg.Debug)
	fmt.Println("Timeout:", cfg.Timeout)
}

struct → YAML

go
	u := User{
		Name:  "Tom",
		Age:   18,
		Admin: true,
	}

	data, err := yaml.Marshal(u)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(data))

go-yaml

"github.com/goccy/go-yaml"