Created
February 4, 2020 07:06
-
-
Save nondanee/f5e7d8fc870e2521d1273fef64d42716 to your computer and use it in GitHub Desktop.
Reverse Proxy Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const url = require('url') | |
const net = require('net') | |
const http = require('http') | |
const https = require('https') | |
const [HOST, PORT = 8000] = process.argv.slice(2) | |
const target = url.parse(HOST.startsWith('http') ? HOST : `http://${HOST}`) | |
console.log('Reverse proxy', target.href, '@', PORT) | |
const server = http.createServer().listen(parseInt(PORT)) | |
server.on('request', (req, res) => { | |
req.pipe( | |
(target.protocol === 'http:' ? http : https) | |
.request({ | |
...url.parse(target.resolve(req.url)), | |
host: target.hostname, | |
method: req.method, | |
headers: { | |
...req.headers, | |
host: target.hostname | |
} | |
}) | |
.on('response', proxyRes => { | |
console.log(req.method, req.url, proxyRes.statusCode) | |
res.writeHead(proxyRes.statusCode, proxyRes.headers) | |
proxyRes.pipe(res) | |
}) | |
.on('error', () => res.end()) | |
) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment