(Go) How to use toml files?

前端 未结 5 1109
长发绾君心
长发绾君心 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:09

    A small update for the year 2019 - there is now newer alternative to BurntSushi/toml with a bit richer API to work with .toml files:

    pelletier/go-toml (and documentation)

    For example having config.toml file (or in memory):

    [postgres]
    user = "pelletier"
    password = "mypassword"
    

    apart from regular marshal and unmarshal of the entire thing into predefined structure (which you can see in the accepted answer) with pelletier/go-toml you can also query individual values like this:

    config, err := toml.LoadFile("config.toml")
    
    if err != nil {
        fmt.Println("Error ", err.Error())
    } else {
    
        // retrieve data directly
    
        directUser := config.Get("postgres.user").(string)
        directPassword := config.Get("postgres.password").(string)
        fmt.Println("User is", directUser, " and password is", directPassword)
    
        // or using an intermediate object
    
        configTree := config.Get("postgres").(*toml.Tree)
        user := configTree.Get("user").(string)
        password := configTree.Get("password").(string)
        fmt.Println("User is", user, " and password is", password)
    
        // show where elements are in the file
    
        fmt.Printf("User position: %v\n", configTree.GetPosition("user"))
        fmt.Printf("Password position: %v\n", configTree.GetPosition("password"))
    
        // use a query to gather elements without walking the tree
    
        q, _ := query.Compile("$..[user,password]")
        results := q.Execute(config)
        for ii, item := range results.Values() {
            fmt.Println("Query result %d: %v", ii, item)
        }
    }
    

    UPDATE

    There is also spf13/viper that works with .toml config files (among other supported formats), but it might be a bit overkill in many cases.

提交回复
热议问题