Skip to content

Instantly share code, notes, and snippets.

@nondanee
Created July 20, 2021 13:06
Show Gist options
  • Save nondanee/a2dd00a0bcd5fcef7ee4ef872a57e4a0 to your computer and use it in GitHub Desktop.
Save nondanee/a2dd00a0bcd5fcef7ee4ef872a57e4a0 to your computer and use it in GitHub Desktop.
http+websockt reverser proxy
const URL = require('url')
const HTTP = require('http')
const QUERY = require('querystring')
const port = parseInt(process.argv[2]) || 8223
const server = HTTP.createServer().listen(port)
const target = URL.parse('http://locahost:8080')
const host = target.host
const modifyHeaders = headers => ({
...headers,
host,
origin: null,
})
const stringifyHeaders = headers => (
QUERY.stringify(
headers,
'\r\n',
': ',
{ encodeURIComponent: _ => _ }
)
)
const createProxyReq = (req) => (
HTTP.request({
...URL.parse(target.resolve(req.url)),
method: req.method,
headers: modifyHeaders(req.headers),
})
)
// http
server.on('request', (req, res) => {
if (!req.url.startsWith('/')) return res.end('invalid')
const proxyReq = createProxyReq(req)
.on('response', proxyRes => {
res.writeHead(proxyRes.statusCode, proxyRes.headers)
proxyRes
.pipe(res)
.on('error', () => res.end())
})
.on('error', () => res.end())
req
.pipe(proxyReq)
.on('error', () => res.end())
})
// websocket
server.on('upgrade', (req, socket, head) => {
createProxyReq(req)
.on('upgrade', (proxyRes, proxySocket, proxyHead) => {
if ((head || {}).length) socket.unshift(head)
if ((proxyHead || {}).length) proxySocket.unshift(proxyHead)
socket.write(
[
'HTTP/1.1 101 Switching Protocols',
stringifyHeaders(proxyRes.headers),
'',
'',
]
.join('\r\n')
)
proxySocket
.pipe(socket)
.on('error', () => socket.end())
socket
.pipe(proxySocket)
.on('error', () => socket.end())
})
.on('error', () => socket.end())
.end()
})
console.log(`HTTP Server running @ http://0.0.0.0:${port}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment