golang 常用配置文件


yaml格式 toml格式 ini格式 需要第三方库
json格式 xml格式  不需要第三方库

yaml配置文件

使用 github 第三方开源gopkg.in/yaml.v2
下载 go get gopkg.in/yaml.v21
新建conf.yaml文件
host: localhost:3306
user: tigerwolfc
pwd: 654321
dbname: tablename
冒号后面必须有一个空格 以user: tigerwolfc为例
user: tigerwolfc//冒号后面有空格
在程序main.go使用配置文件获取参数
package main
import (
    "io/ioutil"
    "gopkg.in/yaml.v2"
    "fmt"
)
func main() {
   var c conf
   conf:=c.getConf()
   fmt.Println(conf.Host)
}
type conf struct {
    Host string `yaml:"host"`
    User string `yaml:"user"`
    Pwd string `yaml:"pwd"`
    Dbname string `yaml:"dbname"`
}
func (c *conf) getConf() *conf {
    yamlFile, err := ioutil.ReadFile("conf.yaml")
    if err != nil {
        fmt.Println(err.Error())
    }
    err = yaml.Unmarshal(yamlFile, c)
    if err != nil {
        fmt.Println(err.Error())
    }
    return c
}
运行main.go 打印出配置文件中user的值tigerwolfc

toml配置文件

TOML 目标是成为一个极简的配置文件格式
TOML 被设计成 无歧义地被映射为哈希表 从而被多种语言解析 使用第三方库 github.com/BurntSushi/toml
下载 go get github.com/BurntSushi/toml
conf.toml 文件
# id
ID = 3
# name
Name = "TigerwolfC"
# weight
Weight = 58
# books
Books = ["Golang", "C++", "Python"]
Sex = true
#friend Friend都可以
[friend]
Age = 28
Name = "chen_peggy"
细节点
结构体的成员首字母大写
配置文件的配置项须与结构体成员名一样
支持bool  int float 字符串 字符串数组 等 也可以包含其他结构体 如[Friend]
package main
import (
    "fmt"
    "github.com/BurntSushi/toml"
    "log"
)
type Person struct {
    ID     uint32    
    Sex    bool    
    Name   string    
    Weight float32    
    Friend *Friends    
    Books  []string
}     
type Friends struct {    
    Age  int    
    Name string
}
func test_toml() {
    var cp Person
    var path string = "./conf.toml"
    if _, err := toml.DecodeFile(path, &cp); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%v %v\\n", cp.Name, cp.Friend.Name)
}
func main() {
    test_toml()
}

json配置文件

JSON(JavaScript Object Notation, JS 对象标记) 轻量级的数据交换格式
简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言
易于人阅读和编写 同时也易于机器解析和生成 并有效地提升网络传输效率
conf.json内容
{ "enabled": true, "path": "/usr/local"}
新建main.go 键入内容
package main
import (
    "encoding/json"
    "fmt"
    "os"
)
type configuration struct {
    Enabled bool
    Path    string
}
func main() {
    file, _ := os.Open("conf.json")
    defer file.Close()
    decoder := json.NewDecoder(file)
    conf := configuration{}
    err := decoder.Decode(&conf)
    if err != nil {
        fmt.Println("Error:", err)
    }
    fmt.Println(conf.Path)
}

xml配置文件

可扩展标记语言 标准通用标记语言的子集 是一种用于标记电子文件使其具有结构性的标记语言
conf.xml 内容
<?xml version="1.0" encoding="UTF-8" ?>
<Config>
   <enabled>true</enabled>
   <path>/usr/local</path>
</Config>
新建main.go 键入内容
package main
import (
    "encoding/xml"
    "fmt"
    "os"
)
type configuration struct {
    Enabled bool   `xml:"enabled"`
    Path    string `xml:"path"`
}
func main() {
    xmlFile, err := os.Open("conf.xml")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer xmlFile.Close()
    var conf configuration
    if err := xml.NewDecoder(xmlFile).Decode(&conf); err != nil {
        fmt.Println("Error Decode file:", err)
        return
    }
    fmt.Println(conf.Enabled)
    fmt.Println(conf.Path)
}

ini配置文件

INI文件格式是某些平台或软件上的配置文件的非正式标准
以节(section)和键(key)构成
常用于微软Windows操作系统中
这种配置文件的文件扩展名多为INI 故名
使用第三方库 go get gopkg.in/gcfg.v1
conf.ini 内容
; A comment line
[Section]
enabled = true
path = /usr/local # another comment
新建main.go 键入代码
package main
import (
    "fmt"
    "gopkg.in/gcfg.v1"
)
func main() {
    config := struct {
        Section struct {
            Enabled bool
            Path    string
        }
    }{}
    err := gcfg.ReadFileInto(&config, "conf.ini")
    if err != nil {
        fmt.Println("Failed to parse config file: %s", err)
    }
    fmt.Println(config.Section.Enabled)
    fmt.Println(config.Section.Path)
}



golang 常用配置文件和golang-config-file相关