Skip to content

Instantly share code, notes, and snippets.

@fox3000foxy
Created April 20, 2025 08:17
Show Gist options
  • Save fox3000foxy/bded543ec13532af8ddc2de614b74055 to your computer and use it in GitHub Desktop.
Save fox3000foxy/bded543ec13532af8ddc2de614b74055 to your computer and use it in GitHub Desktop.
const http = require('http');
const https = require('https');
const { URL } = require('url');
function createProxy(targetBase) {
const targetBaseUrl = new URL(targetBase);
return async function (req, res, next) {
try {
// Reconstitue l'URL finale avec le path et les query params
const targetPath = req.originalUrl.replace(req.baseUrl, '') || '/';
const query = req.url.includes('?') ? req.url.split('?')[1] : '';
const targetUrl = new URL(targetPath, targetBaseUrl);
if (query) targetUrl.search = '?' + query;
// Choisir le bon module HTTP
const client = targetUrl.protocol === 'https:' ? https : http;
// Lire le corps de la requête s'il y en a un
const chunks = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => {
const body = Buffer.concat(chunks);
// Préparer les options de la requête sortante
const options = {
method: req.method,
headers: {
...req.headers,
host: targetUrl.host, // remplace l'en-tête Host
},
};
const proxyReq = client.request(targetUrl, options, proxyRes => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});
proxyReq.on('error', err => {
console.error('Proxy error:', err);
res.statusCode = 502;
res.end('Proxy Error');
});
// Transmet le corps s’il existe
if (body.length) {
proxyReq.write(body);
}
proxyReq.end();
});
} catch (err) {
console.error('Internal proxy error:', err);
res.statusCode = 500;
res.end('Internal Server Error');
}
};
}
module.exports = createProxy;
/*
Exemple usage:
const express = require('express');
const bodyParser = require('body-parser');
const createProxy = require('./createProxy');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Exemple : proxifier /github → https://github.com
app.use('/github', createProxy('https://github.com'));
app.use('/httpbin', createProxy('https://httpbin.org'));
app.listen(3000, () => {
console.log('Proxy server listening on http://localhost:3000');
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment