一个简单的例子学会github-repository的webhook

8次阅读

共计 2111 个字符,预计需要花费 6 分钟才能阅读完成。

github 的 webhook 是个有用的功能,允许开发人员指定一个服务器的 url。当开发者对 github 仓库施加操作,比如提交代码,创建 issue 时,github 网站会自动向该 url 指定的服务器推送事件。借助 webhook,我们可以实现很多自动化流程。比如部署一个应用在 AWS 上,本地提交代码后,github 网站自动触发 webhook,调用 AWS 上应用的逻辑,在 AWS 上将本地提交的最新代码用 git pull 抓取到 AWS 上并重新部署。

下面我们通过一个具体的例子来学习 github webhook 的用法。

新建一个 github 仓库,点击 Settings 链接:

在 Payload url 里指定一个应用的 url,该 url 对应的应用监听 github 网站推送的事件。

Content Type 指定成 application/json 便于我们在 nodejs 应用里解析 payload。

创建后点 Add webhook 保存,github 会发送一个 json paload 到这个 url 指定的应用上。

在 Recent Deliveries 里查看负载明细:

负载明细如下:

我们现在来做个实验,把 webhook 指定的 url 对应的应用设置一个断点,然后在 github 仓库里新建一个 issue:

断点立即触发了。

从调试器里能观察到这个 create issue 事件的所有负载。

我部署在 AWS 上监听 github webhook 框架推送 github repository 发生变化的事件的应用源代码,可以从我的 github 上获取:
https://github.com/i042416/we…

代码很短,我的同事 Haytham 写的:


var http = require('http')
var createHandler = require('github-webhook-handler')
var handler = createHandler({path: '/push', secret: 'dis-koi'})
 
function run_cmd(cmd, args, callback) {var spawn = require('child_process').spawn;
    var child = spawn(cmd, args);
    var resp = "";

    child.stdout.on('data', function(buffer) {resp += buffer.toString(); });
    child.stdout.on('end', function() {callback (resp) });
}

http.createServer(function (req, res) {handler(req, res, function (err) {
        res.statusCode = 404
        res.end('no such location')
    })
}).listen(8083)
 
handler.on('error', function (err) {console.error('Error:', err.message);
})
 
handler.on('push', function (event) {switch(event.payload.repository.name)
    {
        case 'githubHook':
            //this push event is from my persional github account, as SAP github.tool's github hook do not work, so I use this one to test push event
            console.log("reveive a push event from githubHook");
            run_cmd('sh', ['./webshop.sh'], function(text){console.log(text) });
            break;
        case 'frontend-web':
            //push event from frontend-web
            console.log("reveive a push event from frontend-web");
            run_cmd('sh', ['./webshop.sh'], function(text){console.log(text) });
            break;
        case 'backend-ms':
            //push event from backenf-ms
            console.log("reveive a push event from backend-ms");
            run_cmd('sh', ['./backend_ms.sh'], function(text){console.log(text) });
            break;
    }
})
 
handler.on('issues', function (event) {
    console.log('Received an issue event for %s action=%s: #%d %s',
        event.payload.repository.name,
        event.payload.action,
        event.payload.issue.number,
        event.payload.issue.title);
})

要获取更多 Jerry 的原创文章,请关注公众号 ” 汪子熙 ”:

正文完
 0