yaml格式文件作为配置文件、包管理文件,众多软件都在使用,go 语言通过 “gopkg.in/yaml.v2” 包,可以支持 yaml文件解析和处理。
文件conf.yaml 文件内容如下:robot@ubuntu:~/gomod/src/yaml$ cat conf.yaml
config:
user:
- Tom
- Lily
- Skay
mqtt:
host: localhost:1883
username: test
password: test
http: {port: "8080", host: "127.0.0.1"}
如何使用 "gopkg.in/yaml.v2"包处理这个文件呢,实例代码如下:
实例代码robot@ubuntu:~/gomod/src/yaml$ cat yaml.go
package main
import (
"os"
"log"
"fmt"
"encoding/json"
"gopkg.in/yaml.v2"
)
type HTTP struct {
Port string `yaml:"port"`
Host string `yaml:"host"`
}
type MQ struct {
Host string `yaml:"host"`
Username string `yaml:"username"`
Password string `yaml:"password"`
}
type Debug struct {
User []string `yaml:"user"`
MQTT MQ `yaml:"mqtt"`
Http HTTP `yaml:"http"`
}
type Config struct {
Debug Debug `yaml:"config"`
}
func ReadYamlConfig(path string) (*Config,error){
conf := &Config{}
if f, err := os.Open(path); err != nil {
return nil,err
} else {
yaml.NewDecoder(f).Decode(conf)
}
fmt.Println("conf: ", conf)
return conf,nil
}
func main() {
conf,err := ReadYamlConfig("conf.yaml")
if err != nil {
log.Fatal(err)
}
byts, err := json.Marshal(conf)
if err != nil {
log.Fatal(err)
}
fmt.Println("string:",string(byts))
}
实例运行结果
如下:
robot@ubuntu:~/gomod/src/yaml$ ls
conf.yaml go.mod go.sum yaml.go
robot@ubuntu:~/gomod/src/yaml$ go run yaml.go
conf: &{{[Tom Lily Skay] {localhost:1883 test test} {8080 127.0.0.1}}}
string: {"Debug":{"User":["Tom","Lily","Skay"],"MQTT":{"Host":"localhost:1883","Username":"test","Password":"test"},"Http":{"Port":"8080","Host":"127.0.0.1"}}}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)