Go解析yaml文件

本文介绍了如何在Go中解析yaml文件。首先,由于安装yaml包可能出现问题,可以通过下载源码并手动编译解决。接着,文章展示了`main.go`的代码结构,说明了yaml文件的示例`cluster.yaml`,并提到了解析后的输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

包准备

首先安装解析yaml文件的包

go get gopkg.in/yaml.v2

但是可能会无法安装成功,报错显示go get unrecognized import path "gopkg.in/yaml.v2"
通过下载编译源代码的方式解决:
go/src路径下新建一个文件gopkg.in,将代码下载到go/src/gopkg.in

git config  --global   http.sslVerify "false"
git config --global http.postBuffer 524288000
go env -w GOPROXY=https://goproxy.cn,direct
git clone https://github.com/go-yaml/yaml.git 

或者在https://github.com/go-yaml/yaml上下载zip,解压到该路径下。
之后将yaml的文件名称改为yaml.v2,安装:

cd yaml.v2
go install

main.go

package main
​
import (
    "encoding/json"
    "fmt"
    "gopkg.in/yaml.v2"
    "io/ioutil"
    "log"
    "os"
)//Yaml the yaml file Cluster struct
type Yaml struct {
   
    Clusters Clusters `yaml:"clusters"`
}
type Clusters struct {
   
    Services []Services `yaml:"services"`
}
type Services struct {
   
    Name       string `yaml:"service_name"`
    Ip         string `yaml:"ipaddr"`
    Username   string `yaml:"username"`
    Passwd     string `yaml:"passwd"`
    Ports      []Ports  `yaml:"ports,omitempty"`
}
type  Ports    struct{
   
Port      string 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值