(Go) How to use toml files?

前端 未结 5 1108
长发绾君心
长发绾君心 2021-02-15 17:47

As title, I want to know how to use toml files from golang.

Before that, I show my toml examples. Is it right?

[datatitle]
enable = true
userids = [
             


        
5条回答
  •  失恋的感觉
    2021-02-15 18:07

    First get BurntSushi's toml parser:

    go get github.com/BurntSushi/toml

    BurntSushi parses toml and maps it to structs, which is what you want.

    Then execute the following example and learn from it:

    package main
    
    import (
        "github.com/BurntSushi/toml"
        "log"
    )
    
    var tomlData = `title = "config"
    [feature1]
    enable = true
    userids = [
      "12345", "67890"
    ]
    
    [feature2]
    enable = false`
    
    type feature1 struct {
        Enable  bool
        Userids []string
    }
    
    type feature2 struct {
        Enable bool
    }
    
    type tomlConfig struct {
        Title string
        F1    feature1 `toml:"feature1"`
        F2    feature2 `toml:"feature2"`
    }
    
    func main() {
        var conf tomlConfig
        if _, err := toml.Decode(tomlData, &conf); err != nil {
            log.Fatal(err)
        }
        log.Printf("title: %s", conf.Title)
        log.Printf("Feature 1: %#v", conf.F1)
        log.Printf("Feature 2: %#v", conf.F2)
    }
    

    Notice the tomlData and how it maps to the tomlConfig struct.

    See more examples at https://github.com/BurntSushi/toml

提交回复
热议问题