Hi all, thanks for all your amazing contribution to this open source project.
I am facing an issue that I think that has not been addressed or is just very well hidden into the docs.
If I have the following code:
type kiwi struct {
Key1 string
Key3 string
}
func main() {
var blob = `
[kiwi]
key1 = "value1"
key2 = "value2"
key3 = "value3"
`
var conf map[string]kiwi
md, err := toml.Decode(blob, &conf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Undecoded keys: %q\n", md.Undecoded())
//Undecoded keys: ["kiwi.key2"]
}
which decodes the key2
value under the [kiwi]
table name. If I change the table name to something like [ki]
it will still resolve ["ki.key2]"
as the undecoded, when in reality it should detect that all the keys are from a different table, so all of them should be marked as undecoded.
Is there any way of reliably undecoding a toml document which is behind one (or more) tables?
What I mean by reliably undecoding is to also check the name of the table and to verify if the name of the table is the same as the struct which is used to decode it.
I have followed and adapted the same tutorial shown on your docs: https://godocs.io/github.com/BurntSushi/toml#example-package--StrictDecoding
If this is somewhat achievable, please you should add it into the docs so more people searching for this kind of stuff can get their issues resolved as fast as possible.
Best regards.
Exactly, that's it! @arp242
Coolio, just making sure.
You need to use a struct in that case, rather than a map. This way you can specify which tables you want. For example:
package main
import (
"fmt"
"github.com/BurntSushi/toml"
)
type (
config struct {
Kiwi kiwi
}
kiwi struct {
Key1 string
Key3 string
}
)
func main() {
try(`
[kiwi]
key1 = "value1"
key2 = "value2"
key3 = "value3"
`)
try(`
[ki]
key1 = "value1"
key2 = "value2"
key3 = "value3"
`)
}
func try(blob string) {
var conf config
md, err := toml.Decode(blob, &conf)
if err != nil {
panic(err)
}
fmt.Printf("Decoded: %#v\nUndecoded keys: %q\n", conf.Kiwi, md.Undecoded())
}
Outputs:
Decoded: main.kiwi{Key1:"value1", Key3:"value3"}
Undecoded keys: ["kiwi.key2"]
Decoded: main.kiwi{Key1:"", Key3:""}
Undecoded keys: ["ki" "ki.key1" "ki.key2" "ki.key3"]
You don't need to create two types, can also use:
type config struct {
Kiwi struct {
Key1 string
Key3 string
}
}
Remember that you need to export the Kiwi
field on the config
type.
Owner Name | BurntSushi |
Repo Name | toml |
Full Name | BurntSushi/toml |
Language | Go |
Created Date | 2013-02-26 |
Updated Date | 2023-03-20 |
Star Count | 4154 |
Watcher Count | 84 |
Fork Count | 518 |
Issue Count | 15 |