Created
February 12, 2025 12:47
-
-
Save victoralvesf/ca1e52d09daf84b1181fe6fcd6e65976 to your computer and use it in GitHub Desktop.
Simple Express Proxy
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
| import express from 'express' | |
| import http from 'http' | |
| import https from 'https' | |
| const app = express() | |
| const PORT = 12720 | |
| const setHeaders = (headers) => { | |
| const headersToPass = { | |
| 'Content-Type': headers['content-type'] ?? 'application/octet-stream', | |
| 'Content-Length': headers['content-length'], | |
| 'Accept-Ranges': headers['accept-ranges'], | |
| 'Cache-Control': headers['cache-control'] ?? 'no-cache', | |
| } | |
| Object.keys(headersToPass).forEach((key) => { | |
| if (headersToPass[key] === undefined) { | |
| delete headersToPass[key] | |
| } | |
| }) | |
| return headersToPass | |
| } | |
| const handleRedirect = (redirectUrl, res, protocol) => { | |
| protocol | |
| .get(redirectUrl, (redirectResponse) => { | |
| const { statusCode, headers } = redirectResponse | |
| if (statusCode >= 300 && statusCode < 400) { | |
| const redirectUrl = headers.location | |
| handleRedirect(redirectUrl, res, protocol) | |
| } else { | |
| res.writeHead(statusCode, setHeaders(headers)) | |
| redirectResponse.pipe(res) | |
| } | |
| }) | |
| .on('error', (err) => { | |
| handleError(err, res, 'Error while redirecting') | |
| }) | |
| } | |
| const handleError = (err, res, message) => { | |
| console.error(err) | |
| res.writeHead(500, { 'Content-Type': 'text/plain' }) | |
| res.end(message) | |
| } | |
| const fetchResource = (url, res) => { | |
| const protocol = url.startsWith('https') ? https : http | |
| console.log('Proxing URL:', decodeURI(url)) | |
| protocol | |
| .get(url, (response) => { | |
| const { statusCode, headers } = response | |
| if (statusCode >= 300 && statusCode < 400) { | |
| const redirectUrl = headers.location | |
| handleRedirect(redirectUrl, res, protocol) | |
| } else { | |
| res.writeHead(statusCode, setHeaders(headers)) | |
| response.pipe(res) | |
| } | |
| }) | |
| .on('error', (err) => { | |
| handleError(err, res, 'Error getting the audio') | |
| }) | |
| } | |
| app.get('/proxy', (req, res) => { | |
| const url = req.query.url | |
| fetchResource(url, res) | |
| }) | |
| app.listen(PORT, () => { | |
| console.log(`Proxy server running on http://localhost:${PORT}`) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment