-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
58 lines (49 loc) · 1.36 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
50
51
52
53
54
55
56
57
var http = require('http');
var url = require('url');
var Feed = require('./rss');
var PORT = process.env.PORT || 8888;
function getFeedUrl(request) {
return url.parse(request.url, true).query.url;
}
function writeError(err, response) {
response.writeHead(500, {
"Content-Type": "text/plain;charset=utf-8",
"Access-Control-Allow-Origin": "*"
});
response.write(err + "\n", function() {
response.end();
});
}
function writeJsonResponse(rss, response) {
response.writeHead(200, {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*"
});
response.write(JSON.stringify(rss));
response.end();
}
function handleRequest(request, response) {
var feedUrl = getFeedUrl(request);
var hasHttp = /^http:\/\/|https:\/\//.test(feedUrl);
if (!hasHttp) {
feedUrl = 'http://' + feedUrl
}
var isHttps = /^https:/.test(feedUrl);
if (isHttps) {
feedUrl = feedUrl.replace(/^https/, "http");
console.log('try connect to non-https:', feedUrl);
}
console.log('try connect to:', feedUrl);
Feed.load(feedUrl, function(err, rss) {
if (err) {
console.log('error', err);
writeError(err, response);
} else {
writeJsonResponse(rss, response);
}
});
}
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("Sever started on %s", PORT);
});