Skip to content

Instantly share code, notes, and snippets.

@nondanee
Created February 4, 2020 07:06
Show Gist options
  • Save nondanee/f5e7d8fc870e2521d1273fef64d42716 to your computer and use it in GitHub Desktop.
Save nondanee/f5e7d8fc870e2521d1273fef64d42716 to your computer and use it in GitHub Desktop.
Reverse Proxy Server
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