1、config.yaml配置文件内容假设如下
name: "example"
version: 1.0
settings:
timeout: 30
debug: true
features:
- feature1
- feature2
2、定义结构体
go语言定义结构体匹配yaml内容
package main
import (
"fmt"
"log"
"os"
"gopkg.in/yaml.v2" // 或者 "github.com/go-yaml/yaml"
)
type Config struct {
Name string `yaml:"name"`
Version float64 `yaml:"version"`
Settings struct {
Timeout int `yaml:"timeout"`
Debug bool `yaml:"debug"`
Features []string `yaml:"features"`
} `yaml:"settings"`
}
3、读取并解析 YAML 文件
读取 config.yaml 文件,并将其解析为 Config 结构体
func loadConfig(filename string) (*Config, error) {
// 读取文件内容
data, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
// 解析 YAML 数据
var config Config
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to unmarshal YAML: %w", err)
}
return &config, nil
}
func main() {
// 加载配置
config, err := loadConfig("config.yaml")
if err != nil {
log.Fatalf("Error loading config: %v", err)
}
// 打印配置
fmt.Printf("%+v\n", config)
}
4、整体示例代码
package main
import (
"fmt"
"log"
"os"
"github.com/go-yaml/yaml"
)
type Config struct {
Name string `yaml:"name"`
Version float64 `yaml:"version"`
Settings struct {
Timeout int `yaml:"timeout"`
Debug bool `yaml:"debug"`
Features []string `yaml:"features"` // 确保这里是 []string
} `yaml:"settings"`
}
func loadConfig(filename string) (*Config, error) {
// 读取文件内容
data, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
// 解析 YAML 数据
var config Config
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to unmarshal YAML: %w", err)
}
return &config, nil
}
func main() {
// 加载配置
config, err := loadConfig("config.yaml")
if err != nil {
log.Fatalf("Error loading config: %v", err)
}
// 打印配置
fmt.Printf("%+v\n", config)
}