Golang 讀取yaml文件


1、新建 conf.yaml 文件

database:
  dbtype: mysql
  dbname: database
  table: table
  username: username
  password: password

application:
  port: 8000

2、新建 conf.go 文件

//package conf
package main

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

type Conf struct {
    Database Database
    Application Application
}

type Database struct {
    Dbtype string
    Dbname string
    Table string
    Username string
    Password string
}

type Application struct {
    Port string
}

func GetConf() Conf {
    var conf Conf
// 加載文件 yamlFile, err :
= ioutil.ReadFile("/Users/root/Desktop/home/workStations/GoProjects/src/oa.yuchan.cn/conf/conf.yaml") if err != nil { fmt.Println(err.Error()) }
// 將讀取的yaml文件解析為響應的 struct err
= yaml.Unmarshal(yamlFile, &conf) if err != nil { fmt.Println(err.Error()) } return conf } func main() { fmt.Println(GetConf().Database.Dbname) }

 

user


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM