GO語言: 讀取設定檔的方式toml

來源:互聯網
上載者:User

最近go語言項目中用到讀取設定檔,如下:
使用這個"github.com/BurntSushi/toml"
設定檔如下:conf.toml

# idID = 1# nameName = "name1"# weightWeight = 1.7# booksBooks = ["a", "b", "c"]Sex = true#friend Friend都可以[friend]Age = 32Name = "xio"

代碼如下 readConf.go:

package confimport ("fmt""github.com/BurntSushi/toml""io/ioutil""os")// persontype Person struct {ID     uint32Sex    boolName   stringWeight float32Friend *FriendsBooks  []string}// friendstype Friends struct {Age  intName string}func ReadConf(fname string) (p *Person, err error) {var (fp       *os.Filefcontent []byte)p = new(Person) // &Person{}if fp, err = os.Open(fname); err != nil {fmt.Println("open error ", err)return}if fcontent, err = ioutil.ReadAll(fp); err != nil {fmt.Println("ReadAll error ", err)return}if err = toml.Unmarshal(fcontent, p); err != nil {fmt.Println("toml.Unmarshal error ", err)return}return}

測試代碼如下 readConf_test.go:

package confimport "testing"func TestReadConf(t *testing.T) {p, err := ReadConf("./conf.toml")if err != nil {t.Logf("%v", err)}t.Logf("person %v", p)t.Logf("person.friend %v", p.Friend)}

輸出結果為:

[ `go test -v` | done: 2.6748515s ]  === RUN   TestReadConf  --- PASS: TestReadConf (0.00s)    readConf_test.go:11: person &{1 true name1 1.7 0x1218c570 [a b c]}    readConf_test.go:12: person.friend &{32 xio}  PASS  ok    goProgram/conf  0.458s


細節點:

1 結構體的成員首字母大寫
2 設定檔的配置項須與結構體成員名一樣
3 支援bool, int, float , 字串,字串數組...等,也可以包含其他結構體 如[Friend] 

附:學習連結
https://item.congci.com/-/content/toml-ji-jian-de-peizhiwenjian-geshi
https://github.com/toml-lang/toml

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.