-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01.get-public-ip.js
34 lines (29 loc) · 935 Bytes
/
01.get-public-ip.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
addEventListener('fetch', event => {
const { request } = event;
if (request.method === 'GET') {
event.respondWith(getClientIP(request));
} else {
event.respondWith(sendErrorResponse(`Method not allowed: ${request.method}`, 405));
}
});
async function getClientIP(request) {
const clientIP = request.headers.get('CF-Connecting-IP') || 'IP not found';
return new Response(clientIP, {
status: 200,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'X-Content-Type-Options': 'nosniff',
}
});
}
function sendErrorResponse(message, statusCode = 400) {
const errorResponse = { error: message };
return new Response(JSON.stringify(errorResponse), {
status: statusCode,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache, no-store, must-revalidate',
}
});
}