1

Is there a way to decode custom types with hcl/v2? I'm looking for something equivalent to encoding/json.Unmarshaler. I've tried implementing encoding.TextUnmarshaler which didn't work.

Here's an example use-case.

type Duration struct {
   time.Duration
}

func (d *Duration) UnmarshalText(data []byte) error {
    d0, err := time.ParseDuration(string(data))
    if err != nil {
        return err
    }
    d.Duration = d0
    return nil
}

Note: I'm using v2

Ilia Choly
  • 18,070
  • 14
  • 92
  • 160
  • Do you mean to Unmarshal an attribute in your HCL to a custom go type? Like if you wanted to have a go time.Duration as an attribute value in your HCL? – duhkota Apr 05 '22 at 22:12

1 Answers1

-2

https://pkg.go.dev/github.com/hashicorp/hcl/v2@v2.5.0/hclsimple?tab=doc#example-package-NativeSyntax

Should be what you need.

Taken from documentation:

type Config struct {
    Foo string `hcl:"foo"`
    Baz string `hcl:"baz"`
}

const exampleConfig = `
    foo = "bar"
    baz = "boop"
    `

var config Config
err := hclsimple.Decode(
    "example.hcl", []byte(exampleConfig),
    nil, &config,
)
if err != nil {
    log.Fatalf("Failed to load configuration: %s", err)
}
fmt.Printf("Configuration is %v\n", config)
Richard
  • 414
  • 6
  • 16