Webhook
1️⃣ Webhook이란?
웹 훅(Webhook)은 이벤트 기반의 HTTP 콜백 메커니즘으로, 특정 이벤트가 발생했을 때 사전에 지정된 URL로 데이터를 자동 전송하는 방식입니다. 실시간 데이터 전달이 가능하고, 폴링(Polling) 방식보다 효율적이며, 다양한 서비스 간 연동에 활용됩니다.
2️⃣ Webhook 동작 방식
- 이벤트 발생: 특정 시스템에서 이벤트가 발생 (ex. 새로운 주문 생성, GitHub에서 코드 푸시 등)
- Webhook 트리거: 사전에 설정된 엔드포인트(URL)로 HTTP 요청 전송
- 데이터 전달: 일반적으로
POST요청으로 JSON 또는 XML 데이터를 전송 - 응답 처리: Webhook 수신 서버에서 데이터를 처리하고 필요한 작업 수행
예제: GitHub Webhook
✔️ GitHub에서 새로운 커밋이 발생하면, Webhook을 통해 JSON 데이터를 지정된 서버로 전송합니다.
3️⃣ Node.js에서 Webhook 구현하기
🔹 Webhook 엔드포인트 개발 (Node.js + Express)
// 헬스 체크 API 호출 예시
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios'); // API 호출을 위해 axios 사용
const app = express();
const port = 3000;
// JSON 데이터를 파싱할 수 있게 설정
app.use(bodyParser.json());
// 웹훅을 수신하는 엔드포인트 설정
app.post('/webhook', async (req, res) => {
// GitHub 또는 GitLab에서 보내는 데이터
const webhookData = req.body;
console.log('Received Webhook:', webhookData);
// 웹훅의 종류에 따라 처리
if (webhookData.ref) {
// 예: GitHub 푸시 이벤트 처리
console.log('Push event received!');
// 헬스체크 API 호출 (API URL과 인증을 적절히 설정)
try {
const healthCheckResponse = await axios.get('https://your-api-url/healthcheck');
console.log('Health Check Result:', healthCheckResponse.data);
} catch (error) {
console.error('Error checking health:', error);
}
}
// 응답 보내기
res.status(200).send('Webhook received successfully!');
});
// 서버 시작
app.listen(port, () => {
console.log(`Webhook server listening at http://localhost:${port}`);
});
✔️ /webhook 엔드포인트에서 Webhook 데이터를 수신하고 로그 출력