我将使用此存储库解析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.")
}
}
Run Code Online (Sandbox Code Playgroud)
log_dir在这种情况下,我该如何解析?
github.com/hashicorp/hcl/hcl/parser是一个低级软件包。请改用高级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)
}
Run Code Online (Sandbox Code Playgroud)
如果您真的想自己处理AST,也可以使用DecodeObject。