Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Go) How to use toml files?

Tags:

go

toml

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 = [
    "12345", "67890"
]
    [datatitle.12345]
    prop1 = 30
    prop2 = 10

    [datatitle.67890]
    prop1 = 30
    prop2 = 10

And then, I want to set these data as type of struct.

As a result I want to access child element as below.

datatitle["12345"].prop1
datatitle["67890"].prop2

Thanks in advance!

like image 567
Harry Avatar asked Dec 16 '15 08:12

Harry


2 Answers

With solution Viper you can use a configuration file in JSON, TOML, YAML, HCL, INI and others properties formats.

Create file:

./config.toml

First import:

import (config "github.com/spf13/viper")

Initialize:

config.SetConfigName("config")
config.AddConfigPath(".")
err := config.ReadInConfig()
if err != nil {             
    log.Println("ERROR", err.Error())
}

And get the value:

config.GetString("datatitle.12345.prop1")
config.Get("datatitle.12345.prop1").(int32)

Doc.: https://github.com/spf13/viper

e.g.: https://repl.it/@DarlanD/Viper-Examples#main.go

like image 98
Darlan D. Avatar answered Oct 20 '22 14:10

Darlan D.


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.

UPDATE 2

Viper is not really an alternative (credits to @GoForth).

like image 39
Sevenate Avatar answered Oct 20 '22 14:10

Sevenate