yaml 文件是目前最常用的配置文件,使用go语言编写代码和工具时,也会用到yaml文件,将服务配置及中间件等信息定义到yaml文件中,后续可根据实际场景来选用。
//先下载外部包 go get -u gopkg.in/yaml.v2
1、定义yaml配置文件
conf/test.yaml
ck: host: 11.11.11.11 port: 9001 database: db2 username: test2 password: 123ck456 user: test password: 123yy456 host: 10.10.10.10 port: 3306 dbname: db1
2、主程序
package main import ( "fmt" "gopkg.in/yaml.v3" "io/ioutil" ) type Conn struct { Ck struct { Host string `yaml:"host"` Port string `yaml:"port"` Database string `yaml:"database"` Username string `yaml:"username"` Password string `yaml:"password"` } } type Mysql struct { User string `yaml:"user"` Password string `yaml:"password"` Host string `yaml:"host"` Port string `yaml:"port"` DBname string `yaml:"dbname"` } const cfgFile = "conf/test.yaml" func main() { data, err := ioutil.ReadFile(cfgFile) //读取配置文件的路径 if err != nil { fmt.Printf("err: %v\n", err) return } var conf Conn if err := yaml.Unmarshal(data, &conf); err != nil { //将yaml文件中的信息反序列化给conf结构体 fmt.Printf("err: %v\n", err) return } yml, _ := yaml.Marshal(conf) //序列化为yaml文件 fmt.Printf("conf: %#v\n", conf) fmt.Printf("%s\n", yml) var confs Mysql if err := yaml.Unmarshal(data, &confs); err != nil { fmt.Printf("err: %v\n", err) return } yaml, _ := yaml.Marshal(confs) fmt.Printf("conf: %#v\n", confs) fmt.Printf("%s\n", yaml) }
3、输出结果
conf: main.Conn{Ck:struct { Host string "yaml:\"host\""; Port string "yaml:\"por t\""; Database string "yaml:\"database\""; Username string "yaml:\"username\""; Password string "yaml:\"password\"" }{Host:"11.11.11.11", Port:"9001", Database: "db2", Username:"test2", Password:"123ck456"}} ck: host: 11.11.11.11 port: "9001" database: db2 username: test2 password: 123ck456 conf: main.Mysql{User:"test", Password:"123yy456", Host:"10.10.10.10", Port:"330 6", DBname:"db1"} user: test password: 123yy456 host: 10.10.10.10 port: "3306" dbname: db1
将yaml文件中的信息反序列化给Config结构体标签:string,err,--,fmt,yaml,conf,Go,password From: https://www.cnblogs.com/Xinenhui/p/16966823.html