hcl v2 golang支持环境变量参考
以前写过简单的hcl 解析,以下是一个关于支持环境变量的处理
参考代码
- go mod
module gihub.com/rongfengliang/hclv2-learning
go 1.14
require (
github.com/hashicorp/hcl/v2 v2.6.0
github.com/zclconf/go-cty v1.5.1 // indirect
)
- main.go
package main
import (
"log"
"os"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsimple"
"github.com/zclconf/go-cty/cty"
)
// Job type
type Job struct {
Type string `hcl:",label"`
Name string `hcl:",label"`
Driver string `hcl:"driver"`
DSN string `hcl:"dsn"`
Query string `hcl:"query"`
Webhook string `hcl:"webhook"`
MyInfo string `hcl:"myinfo"`
Schedule string `hcl:"schedule"`
MessageString string `hcl:"message"`
EngineName string `hcl:"jsengine"`
}
// type userinfo struct {
// name string `cty:"name"`
// age int `cty:"age"`
// }
func main() {
var config struct {
Jobs []*Job `hcl:"job,block"`
}
userinfo := cty.MapVal(map[string]cty.Value{
"USERNAME2": cty.StringVal(os.Getenv("USERNAME2")),
})
err := hclsimple.DecodeFile("config.hcl", &hcl.EvalContext{
Variables: map[string]cty.Value{
"env": userinfo,
},
}, &config)
if err != nil {
log.Fatalf("Failed to load configuration: %s", err)
}
for _, item := range config.Jobs {
log.Printf("%s---%s---%s", item.Type, item.Name, item.MyInfo)
}
}
- hcl 配置
job "http" "demo"{
webhook = "http://127.0.0.1:4195"
driver = "mysql"
dsn = "demo:demo@tcp(127.0.0.1:3306)/demo"
jsengine = "otto"
myinfo = env.USERNAME2
query = <<SQL
SELECT users.* FROM users
SQL
schedule = "* * * * * *"
message = <<JS
if ( $rows.length < 1 ) {
return
}
log("this is a demo")
var msg = "";
_.chain($rows).pluck('name').each(function(name){
msg += name+"--------demo--from otto----";
})
var info = {
msgtype: "text",
text: {
content: msg
}
}
log(JSON.stringify(info))
send(JSON.stringify(info))
JS
}
- 代码说明
hcl 解析支持了EvalContext ,我们可以添加env 的在支持(依赖go cty),这样hcl 配置部分就可以引用env 了
参考资料
https://github.com/hashicorp/hcl/tree/hcl2
https://github.com/zclconf/go-cty