go get -u gopkg.in/yaml.v2
package main
import (
"os"
"log"
"fmt"
"encoding/json"
"gopkg.in/yaml.v2"
)
type Config struct {
Test Test `yaml:"test"`
}
type Test struct {
User []string `yaml:"user"`
MQTT MQ `yaml:"mqtt"`
Http HTTP `yaml:"http"`
}
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"`
}
//read yaml config
//注:path为yaml或yml文件的路径
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)
}
return conf,nil
}
//test yaml
func main() {
conf,err := ReadYamlConfig("D:/test_yaml/test.yaml")
if err != nil {
log.Fatal(err)
}
byts,err := json.Marshal(conf)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(byts))
}
test:
user:
- Tom
- Lily
- Skay
mqtt:
host: localhost:1883
username: test
password: test
http: {port: "8080", host: "127.0.0.1"}
{"Test":{"User":["Tom","Lily","Skay"],"MQTT":{"Host":"localhost:1883","Username":"test","Password":"test"},"Http":{"Port":"8080","Host":"127.0.0.1"}}}