问大伙个 cicd 的问题, 如何用 node 写了一个类似 github 的 webhook 的回调用来触发构建部署?我用 gpt 生成的代码一直不生效

262 天前
 YepW

git 仓库平台用的是阿里云效

我把脚本在服务器上执行后,测试 webhook 一直失败,网上也没查到有用的解决办法

云效的 webhook 配置: url: http://服务器 ip:2333/build secret: xxxx

下面是 gpt 生成的脚本

const http = require('http');
const { exec } = require('child_process');

const PORT = 2333;
const WEBHOOK_SECRET = 'xxxx';

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/build') {
    let body = '';

    req.on('data', (chunk) => {
      body += chunk;
    });

    req.on('end', () => {
      const codeupEventHeader = req.headers['codeup-event'];
      const xCodeupToken = req.headers['x-codeup-token'];

      if (codeupEventHeader === 'Push Hook' && xCodeupToken === WEBHOOK_SECRET) {
        let repoName = '';
        try {
          const data = JSON.parse(body);
          repoName = data.repository.name;
        } catch (error) {
          console.error('无法解析 JSON 数据:', error);
          res.statusCode = 400;
          res.end('无效的 JSON 数据');
          return;
        }

        switch (repoName) {
          case 'fuex-merchant':
            exec('sudo chmod -R 777 /opt/fuex-frontend/fuex-merchant/ && sudo chmod -R 777 /var/www/fuex-frontend/merchant && sudo /opt/fuex-frontend/fuex-merchant/build-prod.sh', (error, stdout, stderr) => {
              if (error) {
                console.error('构建失败:', error);
                res.statusCode = 500;
                res.end('构建失败');
              } else {
                console.log('构建成功');
                res.statusCode = 200;
                res.end('构建成功');
              }
            });
            break;
          default:
            console.error('未知的仓库名称:', repoName);
            res.statusCode = 400;
            res.end('未知的仓库名称');
            break;
        }
      } else {
        console.error('无效的请求');
        res.statusCode = 400;
        res.end('无效的请求');
      }
    });
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
})
server.listen(PORT, '0.0.0.0', () => {
  console.log(`Webhook 服务器运行在端口 ${PORT}`);
})


475 次点击
所在节点    问与答
2 条回复
musi
261 天前
建议你在问 gpt 的时候加个 express
julyclyde
258 天前
1 是否产生了调用
2 调用的参数是否正确

这俩问题是 github 这边的
下面问题是你这边的

3 对于正确的参数,你的回调服务能否正常工作

按边界断开,分别调试

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/975328

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX