Erlo

golang几种常用配置文件使用方法总结(yaml、toml、json、xml、ini)

2021-05-02 18:01:38 发布   450 浏览  
页面报错/反馈
收藏 点赞

  1. yaml配置文件的使用方法总结

首先介绍使用yaml配置文件,这里使用的是github上第三方开源gopkg.in/yaml.v2
第一步:下载

go get gopkg.in/yaml.v21

第二步:新建一个yaml文件,比如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)
}

//profile variables
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

  1. toml配置文件的使用方法总结

TOML 的目标是成为一个极简的配置文件格式。TOML 被设计成可以无歧义地被映射为哈希表,从而被多种语言解析。需要使用第三方库https://github.com/BurntSushi/toml
第一步:下载

go get github.com/BurntSushi/toml

第二部:新建一个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"
)
//Person
type Person struct {
	ID     uint32	
	Sex    bool	
	Name   string	
	Weight float32	
	Friend *Friends	
	Books  []string
} 
	
// friends
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 %vn", cp.Name, cp.Friend.Name)
}
func main() {
    test_toml()
}

/*
result:
TigerwolfC  chen_peggy
 */
--------------------- 
  1. 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)
}
  1. xml配置文件的使用方法总结
    可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。
    新建一个文件名为conf.xml,键入内容:


   true
   /usr/local

新建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)
}
  1. ini配置文件的使用方法总结
    INI文件格式是某些平台或软件上的配置文件的非正式标准,以节(section)和键(key)构成,常用于微软Windows操作系统中。这种配置文件的文件扩展名多为INI,故名。
    新建一个文件名为conf.ini,键入内容:
; A comment line
[Section]
enabled = true
path = /usr/local # another comment

使用第三方库:

go get gopkg.in/gcfg.v1

新建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)
}

输出:
true
/usr/local
如有不对欢迎指正,相互学习,共同进步。

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认