golang幾種常用配置文件使用方法總結(yaml、toml、json、xml、ini)


1,yaml配置文件的使用方法總結

首先介紹使用yaml配置文件,這里使用的是github上第三方開源   gopkg.in/yaml.v2
第一步:下載

go get gopkg.in/yaml.v21

 

import "gopkg.in/yaml.v2"

 

第二步:新建一個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

 

2,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 %v\n", cp.Name, cp.Friend.Name)
}
func main() {
    test_toml()
}

/*
result:
TigerwolfC  chen_peggy
 */

 

 

2,

package  main

import (
    "fmt"
    "github.com/BurntSushi/toml"
)

//訂制配置文件解析載體
type Config struct{
    Database *Database
    SQL *SQL
}

//訂制Database塊
type Database struct {
    Driver    string
    Username  string `toml:"us"` //表示該屬性對應toml里的us
    Password string
}
//訂制SQL語句結構
type SQL struct{
    Sql1 string `toml:"sql_1"`
    Sql2 string `toml:"sql_2"`
    Sql3 string `toml:"sql_3"`
    Sql4 string `toml:"sql_4"`
}

var config *Config=new (Config)
func init(){
    //讀取配置文件
    _, err := toml.DecodeFile("test.toml",config)
    if err!=nil{
        fmt.Println(err)
    }
}
func main() {
      fmt.Println(config)
      fmt.Println(config.Database)
      fmt.Println(config.SQL.Sql1)
}

 

#This file as Config struct

#this block as Database struct
[Database]
driver="jdbc:mysql.jdbc.Driver"
us="ft"
password="123"

#this block as SQL struct
[SQL]
sql_1= "select * from user"
sql_2="updata user set name = 'exo'"
sql_3="delete * from user"
sql_4="Insert into user(id,name) values(5,'ft')"

 

3,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)
}

4,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)
}

5,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)
}

 

原文鏈接:https://blog.csdn.net/wade3015/article/details/83351776

 


免責聲明!

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



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