Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexcambose/7337abbb377bacf296673782217e6f05 to your computer and use it in GitHub Desktop.
Save alexcambose/7337abbb377bacf296673782217e6f05 to your computer and use it in GitHub Desktop.
const express = require('express');
const axios = require('axios');
const mime = require('mime');
const morgan = require('morgan');
const { URL } = require('url');
const app = express();
const port = process.env.PORT || 80;
// app.use(morgan('tiny'));
const regex = /\s+(href|src)=['"](.*?)['"]/g;
const getMimeType = (url, headers) => {
if (url.indexOf('dashboard.oversikt.online/js?') !== -1) return 'application/javascript';
return headers['content-type'];
if (url.indexOf('?') !== -1) {
// remove url query so we can have a clean extension
url = url.split('?')[0];
}
return mime.getType(url) || 'text/html'; // if there is no extension return as html
};
app.get('/', (req, res) => {
const { url } = req.query; // get url parameter
if (!url) {
res.type('text/html');
return res.end('You need to specify <code>url</code> query parameter');
}
axios
.get(url, { responseType: 'arraybuffer' }) // set response type array buffer to access raw data
.then((response) => {
let { data } = response;
const urlMime = getMimeType(url, response.headers); // get mime type of the requested url
// if (urlMime.indexOf('text/html') !== -1) {
// replace links only in html
data = data.toString().replace(regex, (match, p1, p2) => {
let newUrl = '';
if (p2.indexOf('http') !== -1) {
newUrl = p2;
} else if (p2.substr(0, 2) === '//') {
newUrl = 'http:' + p2;
} else if (p2[0] === '/') {
console.log('SLASG', p2);
const searchURL = new URL(url);
newUrl = searchURL.protocol + '//' + searchURL.host + p2;
return ` ${p1}="${newUrl}"`;
} else if (p2.indexOf('/js') !== -1) {
console.log('CUSTOM', p2);
const searchURL = new URL(url);
newUrl = searchURL.protocol + '//' + searchURL.host + p2;
return ` ${p1}="${newUrl}"`;
} else {
const searchURL = new URL(url);
newUrl = searchURL.protocol + '//' + searchURL.host + p2;
}
console.log(p2, p2[0]);
return ` ${p1}="${req.protocol}://${req.hostname}:${port}?url=${newUrl}"`;
});
// }
// if (url.indexOf('dashboard.oversikt.online/js?') !== -1) {
// console.log('info', url, data.length);
// }
res.type(urlMime);
res.send(data);
})
.catch((error) => {
console.log('ERROR', url, error.toString());
});
});
app.listen(port, () => console.log(`Listening on port ${port}!`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment