## 什么是 Webhook
Webhook 是"反向 API"——不是你去轮询服务器,而是事件发生时服务器主动通知你。最常见的场景:Git Push 代码后自动部署到服务器。
## GitHub Webhook 配置
**1. 服务器端创建接收脚本**
```python
from flask import Flask, request
import hmac
import hashlib
import subprocess
app = Flask(__name__)
secret = b"your_webhook_secret"
@app.route("/webhook", methods=["POST"])
def webhook():
signature = request.headers.get("X-Hub-Signature-256")
if not signature:
return "No signature", 403
computed = "sha256=" + hmac.new(secret, request.data, hashlib.sha256).hexdigest()
if not hmac.compare_digest(computed, signature):
return "Invalid signature", 403
subprocess.Popen(["/scripts/deploy.sh"])
return "OK", 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=9000)
```
**2. 部署脚本**
```bash
#!/bin/bash
cd /var/www/my-site
git pull origin main
sudo systemctl restart my-site
```
**3. 在 GitHub 仓库设置 Webhook**
Settings → Webhooks → Add webhook
- URL: `https://yourdomain.com/webhook`
- Content type: `application/json`
- secret: 和脚本中的 secret 一致
- Events: Just the push event
## 轻量方案:webhook 工具
有一个叫 `webhook` 的 Go 工具更简单:
```bash
apt install webhook
```
配置文件 `hooks.json`:
```json
[{
"id": "deploy-blog",
"execute-command": "/scripts/deploy.sh",
"command-working-directory": "/var/www/blog",
"trigger-rule": {
"match": {
"type": "payload-hmac-sha256",
"secret": "your_secret",
"parameter": {
"source": "header",
"name": "X-Hub-Signature-256"
}
}
}
}]
```
启动:`webhook -hooks hooks.json -port 9000 -verbose`
## GitHub Actions 推送部署
```yaml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy via SSH
uses: appleboy/[email protected]
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
script: |
cd /var/www/blog
git pull
```
配置好 Webhook 后,你只需要 git push,剩下的自动完成。