golang基础学习-yaml文件的解析
1.什么是yaml?
官网解释
%YAML 1.2 --- YAML: YAML Ain't Markup Language What It Is: YAML is a human friendly data serialization standard for all programming languages.
2.yaml语法
yaml语法,请参考这位仁兄的,写的很详细。
3. golang解析yaml文件
系统环境: MacOS、vim 8.0 、golang :go version go1.8 darwin/amd64
3.1 创建yaml文件
vim first.yaml
内容如下:
SiteName: seeta SiteAddr: BeiJing Https: true Nginx: Port: 443 LogPath: "/var/log//nginx/nginx.log" Path: "/opt/nginx/"
3.2 go 解析yaml的package
3.2.1 yaml.v2
本文采用 : gopkg.in/yaml.v2
import "gopkg.in/yaml.v2"
3.2 解析yaml文件代码
package main import ( "fmt" "io/ioutil" "gopkg.in/yaml.v2" ) //Nginx nginx 配置 type Nginx struct { Port int `yaml:"Port"` LogPath string `yaml:"LogPath"` Path string `yaml:"Path"` } //Config 系统配置配置 type Config struct{ Name string `yaml:"SiteName"` Addr string `yaml:"SiteAddr"` HTTPS bool `yaml:"Https"` SiteNginx Nginx `yaml:"Nginx"` } func main() { var setting Config config, err := ioutil.ReadFile("./first.yaml") if err != nil { fmt.Print(err) } yaml.Unmarshal(config,&setting) fmt.Println(setting.Name) fmt.Println(setting.Addr) fmt.Println(setting.HTTPS) fmt.Println(setting.SiteNginx.Port) fmt.Println(setting.SiteNginx.LogPath) fmt.Println(setting.SiteNginx.Path) }
函数简介:
- ioutil.ReadFile("./first.yaml") :读取yaml文件信息
- yaml.Unmarshal()
第一个输入参数:获取 ioutil.ReadFile 的值,为[]byte类型
第二个参数输出参数,可以为任意类型。
相关推荐
边城客栈学无止境 2020-07-05
awoyaoc 2020-06-07
mary 2020-05-28
ShiShuo 2020-05-16
OyangYujun 2020-04-10
kjh00abc 2020-03-08
sschencn 2020-02-23
akcsdno 2020-02-18
技术积累LZ 2020-02-14
SDUTACM 2020-01-18
jacktangj 2020-01-09
技术积累LZ 2020-01-08
limx 2019-12-18
kjh00abc 2019-12-15
Cherishyuu 2019-12-11
kjh00abc 2019-12-09