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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| const http = require('http'); const https = require('https'); const httpProxy = require('http-proxy'); const jwt = require('jsonwebtoken'); const Redis = require('ioredis');
const serviceMap = { '/api/users': 'http://users-service:3001', '/api/products': 'http://products-service:3002', '/api/orders': 'http://orders-service:3003' };
const proxy = httpProxy.createProxyServer({});
const redisClient = new Redis({ host: 'redis', port: 6379 });
function authenticate(req, res, next) { const token = req.headers['authorization']; if (!token) { return res.status(401).send('Authentication required'); } try { const decoded = jwt.verify(token.split(' ')[1], 'your-secret-key'); req.user = decoded; next(); } catch (err) { res.status(403).send('Invalid token'); } }
async function rateLimit(req, res, next) { const ip = req.ip; const endpoint = req.path; const key = `${ip}:${endpoint}`; try { const current = await redisClient.incr(key); if (current === 1) { await redisClient.expire(key, 60); } if (current > 100) { return res.status(429).send('Too many requests'); } next(); } catch (err) { console.error('Rate limit error:', err); next(); } }
const server = http.createServer(async (req, res) => { try { const target = Object.keys(serviceMap).find(prefix => req.url.startsWith(prefix)); if (!target) { return res.status(404).send('Service not found'); } await authenticate(req, res, () => {}); await rateLimit(req, res, () => {}); proxy.web(req, res, { target: serviceMap[target], changeOrigin: true, pathRewrite: { [`^${target}`]: '' } }); } catch (err) { console.error('Gateway error:', err); res.status(500).send('Internal server error'); } });
proxy.on('error', (err, req, res) => { console.error('Proxy error:', err); res.status(502).send('Bad Gateway'); });
server.listen(3000, () => { console.log('API Gateway running on port 3000'); });
|