golang yaml使用

config.yaml 文件

mysql:
  host: 192.168.1.300
redis:
  database: 10
mongo:
  host: 192.168.1.300


config.go

package yamlDemo

import (
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

// https://github.com/go-yaml/yaml
// 注意這裏要和 定義級別的對應 這裏 結構 首字符大寫
type Mysql struct {
	Host string `yaml:"host"`
}
type Redis struct {
	Database int `yaml:"database"`
}
type Mongo struct {
	Host string `yaml:"host"`
}
type config struct {
	// 使用匿名字段, 這樣 config 會擁有所有的 字段
	Mysql
	Redis
	Mongo
}

func InitLoadConfig() config { // 初始化數據
	pwd, err := os.Getwd()
	if err != nil {
		panic(err)
		os.Exit(1)
	}
	adsPath := strings.Replace(pwd, "\\", "/", -1)
	aa := filepath.Join(adsPath+"/yamlDemo", "config.yaml")
	yamlFile, err := ioutil.ReadFile(aa)
	if err != nil {
		log.Fatal(err)
	}
	c := config{}
	if err := yaml.Unmarshal(yamlFile, &c); err != nil {
		log.Fatal(err)
	}
	return c
}

調用文件

package main

import (
	"fmt"
	"yangDemo/yamlDemo"
)

func main() {
	aa := yamlDemo.InitLoadConfig()
	fmt.Println(aa)
	fmt.Println("mysql", aa.Mysql.Host)
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章