hcl v2 golang使用参考

最新写的定时关系数据库数据处理的简单应用,使用到了hcl配置管理,目前官方推荐的是v2
以下是关于v2的参考使用

环境准备

  • 项目准备
 
go mod init github.com/rongfengliang/hclv2
go get github.com/hashicorp/hcl/v2
  • 代码
package main
import (
    "log"
    "github.com/hashicorp/hcl/v2/hclsimple"
)
// Job type
type Job struct {
    Name          string `hcl:",label"`
    Driver        string `hcl:"driver"`
    DSN           string `hcl:"dsn"`
    Query         string `hcl:"query"`
    Webhook       string `hcl:"webhook"`
    Schedule      string `hcl:"schedule"`
    MessageString string `hcl:"message"`
    EngineName    string `hcl:"jsengine"`
}
func main() {
    var config struct {
        Jobs map[string]*Job `hcl:"job,block"`
    }
    err := hclsimple.DecodeFile("config.hcl", nil, &config)
    if err != nil {
        log.Fatalf("Failed to load configuration: %s", err)
    }
    for _, item := range config.Jobs {
        log.Printf("%s", item)
    }
}
  • 简单说明
    官方提供了一个hclsimple的配置加载工具函数,很方便
  • 参考配置
 
job "demoapp" {
    webhook = "http://127.0.0.1:4195"
    driver = "mysql"
    dsn = "demo:demo@tcp(127.0.0.1:3306)/demo"
    jsengine = "otto"
    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
}
  • 运行效果
go run main.go

 

 

说明

hcl 做为我们的配置语言,是一个很不错的选择,人性化,同时灵活高效

参考资料

https://github.com/hashicorp/hcl/tree/hcl2

posted on   荣锋亮  阅读(699)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-07-04 chef test-kitchen Could not load the 'vagrant' driver from the load path 问题解决
2018-07-04 prisma graphql 工具基本使用
2018-07-04 postgraphile 基本试用
2015-07-04 图片加载js类库
2015-07-04 js 触摸类库

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示