Skip to content

How to use IsDefined with array of tables? #169

@gorankor

Description

@gorankor

I don't know if this is an issue or just me not knowing how to properly call it, so I apologize if I opened a new issue which is not an issue at all.

I have a config file where I want to specify one section several times:

[[methods]]
foo = "method1"
namespace = "ns1"

[[methods]]
foo = "method2"
namespace = "ns2"`

...

Here's a complete example:

package main

import (
        "fmt"
        "os"
        "github.com/BurntSushi/toml"
)

type confMethod struct {
    Foo         string     `toml:"foo,omitempty"`
    NameSpace   string     `toml:"namespace,omitempty"`
}

// Methods struct - used in include files
type confMethods struct {
    Methods []confMethod     `toml:"methods,omitempty"`
}

func main() {
    var mConf confMethods

    c := `[[methods]]
foo = "method1"
namespace = "root/cimv2"

[[methods]]
foo = "method2"
namespace = "root/cimv2"`

    md, err := toml.Decode(c, &mConf)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s\n", err)
        os.Exit(1)
    }

    fmt.Printf("keys=%s\n", md.Keys())

    if md.IsDefined("methods", "namespace") {
        fmt.Printf("defined\n")
    } else {
        fmt.Printf("not defined\n")
    }
}

This returns "not defined". How can one use IsDefined() in this case? Is it possible at all?

I have tried different usages as the commend above IsDefined() in decode.go says:

md.IsDefined("methods", "namespace")
md.IsDefined("methods", "methods.namespace")
md.IsDefined("methods", "method", "namespace")
md.IsDefined("namespace")

but nothing works.

My real example is a bit more complex, and config parser works as expected when I just blindly assign values from config struct, but I'd like to only do that when something is present in the config file. I can't rely on what Keys() returns as that one is not specific enough, but it at least shows that the keys are there as expected (as the example prints it).

If I look at what is going on in decode.go and compare working (where I use just a simple struct) vs. non-working example, when it works, it gets this type:

map[string]interface {}

But for this failing example it gets:

[]map[string]interface {}

And then it fails here on second (might be third - depends how it gets called obviouslly) loop iteration:

if hash, ok = hashOrVal.(map[string]interface{}); !ok

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions