-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
49 lines (43 loc) · 1.38 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
var express = require("express");
var https = require("https");
var http = require("http");
var stream = require("stream");
var app = express();
app.use(express.static("."));
var tap = new stream.Transform();
tap._transform = function(chunk, encoding, callback) {
console.log(chunk.toString());
callback(null, chunk);
};
var fetch = function(address, req, output) {
var parsed = new URL(address);
var remote = parsed.protocol == "http:" ? http : https;
var { host, pathname, search } = parsed;
var headers = Object.assign({}, req.headers);
delete headers.host;
delete headers.referer;
console.log(`Fetching: ${parsed.toString()}`);
headers["User-Agent"] = "Radio";
var p = remote.get({
host,
path: pathname + search,
headers
}, function(proxied) {
if (proxied.statusCode > 300 && proxied.headers.location) {
console.log(`Redirected from ${parsed.toString()} to ${proxied.headers.location}`);
return fetch(proxied.headers.location, req, output);
}
output.writeHead(proxied.statusCode, proxied.headers);
proxied.pipe(output);
});
p.on("error", err => {
output.writeHead(500);
output.end(JSON.stringify(err));
});
}
app.get("/proxy", function(req, response) {
var url = new URL("http://localhost" + req.url);
var address = url.searchParams.get("url");
fetch(address, req, response);
});
app.listen(process.env.PORT || 8000);