(Go) How to use toml files?

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

    I am using spf13/viper

    3rd packages

    Status Project Starts Forks
    Alive spf13/viper stars stars
    Unmaintained BurntSushi/toml stars stars

    so that is why I choose viper

    usage of viper

    I tried to use a table to put the code and the contents of the configuration file together, but obviously, the editing did not match the final result, so I put the image up in the hope that it would make it easier for you to compare


    package main
    import (
        "github.com/spf13/viper"
        "log"
        "os"
    )
    func main() {
        check := func(err error) {
            if err != nil {
                panic(err)
            }
        }
        myConfigPath := "test_config.toml"
        fh, err := os.OpenFile(myConfigPath, os.O_RDWR, 0666)
        check(err)
        viper.SetConfigType("toml") // do not ignore
        err = viper.ReadConfig(fh)
        check(err)
    
        // Read
        log.Printf("%#v", viper.GetString("title"))                 // "my config"
        log.Printf("%#v", viper.GetString("DataTitle.12345.prop1")) // "30"
        log.Printf("%#v", viper.GetString("dataTitle.12345.prop1")) // "30"  // case-insensitive
        log.Printf("%#v", viper.GetInt("DataTitle.12345.prop1"))    // 30
        log.Printf("%#v", viper.GetIntSlice("feature1.userids"))    // []int{456, 789}
    
        // Write
        viper.Set("database", "newuser")
        viper.Set("owner.name", "Carson")
        viper.Set("feature1.userids", []int{111, 222}) // overwrite
        err = viper.WriteConfigAs(myConfigPath)
        check(err)
    }
    
    title = "my config"
    
    [datatitle]
    
      [datatitle.12345]
        prop1 = 30
    
    [feature1]
      userids = [456,789]
    
    
    database = "newuser"  # New
    title = "my config"
    
    [datatitle]
    
      [datatitle.12345]
        prop1 = 30
    
    [feature1]
      userids = [111,222]  # Update
    
    [owner]  # New
      name = "Carson"
    
    

提交回复
热议问题