WebHook 代码示例

介绍各语言在服务端该如何接收 WebHook 消息。

Node.js 示例代码

var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var process = require('child_process');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data


app.post('/webhook', function(req,res){
    console.log('print', req.body);
    console.info(req.body["token"]);
    if('xxx' === req.body['token'] ){

    console.info(process);
    process.exec('git pull', {'cwd':'/home/coding/workspace'},
            function (error, stdout, stderr) {
                console.log('stdout========================\n' + stdout);
                console.log('stderr========================\n' + stderr);
                if (error !== null) {
                    res.send('<pre>fail!!!\n' + stdout + error + '</pre>');
                } else {
                    res.send('<pre>done!!!\n' + stdout + '</pre>');
                }
            });
    } else {
        console.log(' failed token ')
        res.send('<pre>token不正确?</pre>');
    }
});

app.set('port', 8080);

var server = app.listen( 8080, function() {
    console.log('Listening on port %d', server.address().port);
})

Ruby 示例代码

基于 sinatra 框架实现的 webhook 处理。

#!/usr/bin/env ruby

require "sinatra"
require "json/stream"

  get "/" do
    'Hello world!'
  end
  post "/hook" do
    @text = request.body.read
    @data = JSON::Stream::Parser.parse(@text)
    puts @data['token']
    puts @data['ref']
    puts @data['token']
    puts @data['zen']
    puts @data['commits']
    puts @data['repository']
    puts @data['url']

    if "123" == @data['tokne']
        puts `cd workspace`
        puts `git pull `
    end
  end
  get "/env" do
    content_type :text/plain
    html = ""
    html << "System Environment:\n\n"
    ENV.each do |key, value|
        html << "#{key}: #{value}\n"
    end
    html
  end

PHP 示例代码

<?php
  $pwd = getcwd();
  $command = 'cd ' . $pwd . ' && git pull';
  $output = shell_exec($command);
  print $output;
?>

Others

可以阅读以下内容

在 Coding.net 部署博客并使用 WebHook 实现页面自动更新

利用 Webhook 实现线上服务器自动部署