1. 程式人生 > 其它 >go基礎學習-yaml檔案的解析

go基礎學習-yaml檔案的解析

YAML 是一種簡潔的非標記語言。YAML以資料為中心,使用空白,縮排,分行組織資料,從而使得表示更加簡潔易讀。

1.建立config.yaml

內容如下:

app: api
env: dev
https: true
nginx:
  port: 443
  logPath:  "/var/log//nginx/nginx.log"
  path: "/opt/nginx/"

2.建立config/config.go

內容如下:

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"montitor/global"
)

func GetConfig() {
	config, err := ioutil.ReadFile("config.yaml")    ##讀取yaml檔案資訊
	if err != nil {
		fmt.Print(err)
	}
	yaml.Unmarshal(config, &global.CONFIG)
}

3.建立global/global.go

內容如下:

package global

//Nginx nginx  配置
type Nginx struct {
	Port    int    `yaml:"port"`
	LogPath string `yaml:"logPath"`
	Path    string `yaml:"path"`
}

//Config   系統配置配置
type Config struct {
	Env       string `yaml:"env"`
	App       string `yaml:"app"`
	SiteNginx Nginx  `yaml:"nginx"`
}
###全域性變數 var ( CONFIG = new(Config) )

4.main.go

package main

import (
	"fmt"
	"montitor/config"
	"montitor/global"
)

func main() {
	config.GetConfig()
        fmt.Println(global.CONFIG.Env)
fmt.Println(global.CONFIG.App)
fmt.Println(global.CONFIG.SiteNginx.Port)
fmt.Println(global.CONFIG.SiteNginx.LogPath)
fmt.Println(global.CONFIG.SiteNginx.Path)
}

5.go run main.go

dev
api
443
/var/log//nginx/nginx.log
/opt/nginx/