golang yaml解析

Rainy 2022-8-17 663

yaml 文件

logFile: log/versionserver.log
configFile: conf/agentConf.json
mysql:
  user: root
  passwd: happy@1234
  host: 9.160.160.160:3306
  database: test

golang

package main

import (
	"fmt"
	"log"
	"os"
	"testing"

	"gopkg.in/yaml.v2"
)

type MySQL struct {
	User     string `yaml:"user"`
	Passwd   string `yaml:"passwd"`
	Host     string `yaml:"host"`
	Database string `yaml:"database"`
}

type Client struct {
	LogFile    string `yaml:"logFile"`
	ConfigFile string `yaml:"configFile"`
	Mysql      MySQL  `yaml:"mysql"`
}

//read yaml config
//注:path为yaml或yml文件的路径
func readYamlConfig(path string) (*Client, error) {
	conf := &Client{}
	if f, err := os.Open(path); err != nil {
		return nil, err
	} else {
		yaml.NewDecoder(f).Decode(conf)
	}
	return conf, nil
}

//test yaml
func TestMain(t *testing.T) {
	conf, err := readYamlConfig("./client.yaml")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(conf.ConfigFile)
	fmt.Println(conf.LogFile)
	fmt.Println(conf.Mysql.Database)
	fmt.Println(conf.Mysql.Host)
	fmt.Println(conf.Mysql.Passwd)
	fmt.Println(conf.Mysql.User)

	// byts, err := json.Marshal(conf)
	// if err != nil {
	// 	log.Fatal(err)
	// }

	// fmt.Println(string(byts))
}
最新回复 (0)
返回
发新帖