yaml文件名:agent.yml
agent:
agentName: agent001
location:
type: cdb
env: prod
role: ro
set: tsh2
idc: st4
zone: ap-shanghai-4
hostname: baidu.com
content: register new Agent agent001
注意,空格,不要用tab键
golang文件:main.go文章来源:https://www.toymoban.com/news/detail-702414.html
package main
import (
"fmt"
"os"
"gopkg.in/yaml.v2"
)
type LocationKey struct {
CloudType string `yaml:"type"`
Env string `yaml:"env"`
Role string `yaml:"role"`
Set string `yaml:"set"`
Idc string `yaml:"idc"`
Zone string `yaml:"zone"`
Hostname string `yaml:"hostname"`
}
type Agent struct {
AgentName string `yaml:"agentName"`
AgentKey LocationKey `yaml:"location"`
Content string `yaml:"content"`
}
type as struct {
Magent Agent `yaml:"agent"`
}
func main() {
var a as
data, err := os.ReadFile("./agent.yml")
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(string(data))
err = yaml.Unmarshal(data, &a)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(a)
}
执行:文章来源地址https://www.toymoban.com/news/detail-702414.html
# go mod tidy
# go build main.go
到了这里,关于golang读取yaml文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!