-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
36 lines (27 loc) · 941 Bytes
/
index.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
35
36
const express = require('express');
const { createRateLimiter, checkIp } = require('./index.node');
const app = express();
// Create a Rust rate limiter with configurations.
const rateLimiter = createRateLimiter(100, 60, 10); // 100 requests per minute, 10 burst allowance.
// Middleware for IP rate limiting.
function rateLimitMiddleware(req, res, next) {
const clientIp = req.ip;
const allowed = checkIp(rateLimiter, clientIp);
if (!allowed) {
return res.status(429).json({ error: 'Rate limit exceeded. Try again later.' });
}
next();
}
// Apply the middleware to all routes.
app.use(rateLimitMiddleware);
// Example routes.
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.get('/api', (req, res) => {
res.send({ message: 'This is a rate-limited API route.' });
});
// Start the server.
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});