知識點 讀取配置文件

go語言讀取配置文件
go get https://github.com/aWildProgrammer/fconf
如下演示文件保存爲demo.ini

[mysql]
  db1.Name = testMysqlDB
  db1.Host = 127.0.0.1
  db1.Port = 3306
  db1.User = root
  db1.Pwd = test
  ; 測試INI風格的註釋
  ; 這兩行數據的前前面加入了分號,所以,這些數據被認爲是註釋,將不會影響配置文件正常狀況
[tcp]
  Port=3309
mysql

func main() {
  c, err := fconf.NewFileConf("./demo.ini")
    if err != nil {
      fmt.Println(err)
    return
    }
  fmt.Println(c.String("mysql.db1.Host"))
  fmt.Println(c.String("mysql.db1.Name"))
  fmt.Println(c.String("mysql.db1.User"))
  fmt.Println(c.String("mysql.db1.Pwd"))

  // 取得配置時指定類型
  port, err := c.Int("mysql.db1.Port")
    if err != nil {
      panic("~")
    }
  fmt.Println(port)
}git

 

json使用
JSON(JavaScript Object Notation, JS 對象標記) 是一種輕量級的數據交換格式。它基於 ECMAScript (w3c制定的js規範)的一個子集,
採用徹底獨立於編程語言的文本格式來存儲和表示數據。簡潔和清晰的層次結構使得 JSON 成爲理想的數據交換語言。 易於人閱讀和編寫,
同時也易於機器解析和生成,並有效地提高網絡傳輸效率。github

新建一個文件名爲conf.json,鍵入內容:
{
"enabled": true,
"path": "/usr/local"
}
package mainsql

import (
  "encoding/json"
  "fmt"
  "os"
)編程

type configuration struct {
  Enabled bool
  Path string
}json

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)
}tcp

xml使用
可擴展標記語言,標準通用標記語言的子集,是一種用於標記電子文件使其具備結構性的標記語言。
新建一個文件名爲conf.xml,鍵入內容:
<?xml version="1.0" encoding="UTF-8" ?>
<Config>
  <enabled>true</enabled>
  <path>/usr/local</path>
</Config>編程語言

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)

}

相關文章
相關標籤/搜索