HCL文件中的变量解析问题
时间:2024-02-18
浏览:209
作者:佚名
目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《HCL文件中的变量解析问题》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~
问题内容
我有一个 go 项目,我想在其中读取 hcl 文件。该 hcl 文件包含变量。但是,我无法解析它,并且收到以下错误消息:
variables not allowed; variables may not be used here., and 1 other diagnostic(s)
我的go代码:
package main
import (
"fmt"
"log"
"github.com/hashicorp/hcl/v2/hclsimple"
)
type config struct {
hello string `hcl:"hello"`
world string `hcl:"world"`
message string `hcl:"message"`
}
func main() {
var config config
err := hclsimple.decodefile("test.hcl", nil, &config)
if err != nil {
log.fatalf("failed to load configuration: %s", err)
}
fmt.println(config.message)
}
我的 hcl 文件
hello = "hello"
world = "world"
message = "hello ${world}"
我做错了什么?我的 hcl 语法可能不正确吗?
正确答案
它在语法上是有效的,但并没有按照您期望的方式工作。 hcl 不允许引用 hcl 文件中其他位置定义的任意值。它只允许引用解析器公开的变量。例如,这给出了预期的输出:
ectx := &hcl.EvalContext{Variables: map[string]cty.Value{"world": cty.StringVal("world")}}
err := hclsimple.DecodeFile("test.hcl", ectx, &config)
文档并没有对此说得特别清楚,但相关参考文献位于此处:https://github.com/hashicorp/hcl/blob/main/guide/go_expression_eval.rst#expression-evaluation-modes
好了,本文到此结束,带大家了解了《HCL文件中的变量解析问题》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
热门专题
