谁能帮忙解析一下HCL?

Can anyone help to parse HCL?

我将使用 this repository 解析 HCL 配置文件。

package main

import (
    "fmt"
    hclParser "github.com/hashicorp/hcl/hcl/parser"
)

const (
    EXAMPLE_CONFIG_STRING = "log_dir = \"/var/log\""
)

func main() {
    // parse HCL configuration
    if astFile, err := hclParser.Parse([]byte(EXAMPLE_CONFIG_STRING)); err == nil {
        fmt.Println(astFile)
    } else {
        fmt.Println("Parsing failed.")
    }
}

在这种情况下如何解析 log_dir

github.com/hashicorp/hcl/hcl/parser 是低级包。使用 high-level API 代替:

package main

import (
        "fmt"

        "github.com/hashicorp/hcl"
)

type T struct {
        LogDir string `hcl:"log_dir"`
}

func main() {
        var t T
        err := hcl.Decode(&t, `log_dir = "/var/log"`)
        fmt.Println(t.LogDir, err)
}

如果你真的想自己处理 AST,也可以使用 DecodeObject。