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