const httpPort = 12580;
const exec = require('child_process').exec;
const http = require('http');
const colors = require("colors");
const httpServer = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain;charset=utf-8'
});
if (req.method.toUpperCase() != 'POST' && req.method.toUpperCase() != 'GET') {
res.end("Request by GET/POST only!");
return;
}
switch (req.url) {
case "/favicon.ico":
// ignore the web icon request
res.end();
break;
default:
debug("Webhook run " + ("async").red + " ---> " + req.url);
res.end("Webhook Success");
exec("sh /home/wwwroot/" + req.url, function(err, stdout, stderr) {
if (err) {
console.log(stdout.red);
debug("Webhook error!");
} else {
console.log(stdout.blue);
debug("Webhook success!");
}
});
}
});
httpServer.listen(httpPort);
debug("Webhook start success!");
function debug(msg) {
console.log(getTime().yellow + "\t" + msg);
}
function getTime() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
return hours + ":" + minutes + ":" + seconds;
}
npm install -g pm2@2.10.2
这里遇到个坑,高版本的PM2死活跑起来有问题,不知道为什么,切回我常用的版本就没问题...
可自定义访问端口,需要防火墙开启端口访问,可Nginx反向代理。
当执行脚本的执行时间过长,可能导致http请求超时,这个脚本默认支持async异步请求方式访问。 如果需要同步操作,可调整res.end()方法的位置到执行GIT pull之前。
推荐将webhook加入到开机启动项,保证webhook保持在线