-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshortener.js
65 lines (59 loc) · 1.85 KB
/
shortener.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
58
59
60
61
62
63
64
65
var http = require('http');
var info = require('./lib/info/info.js');
var shortenerdb = require('./lib/shortenerdb/shortenerdb.js');
var server = http.createServer(function(req, res) {
//if no parameters -> send info page
if (req.url === '/') {
info(req, res);
} else if (req.url.indexOf('/new/') === 0) {
// url insertion
var allowInvalid = false;
var original = '';
// check if invalid urls are allowed
if (req.url.indexOf('?allow=true') === (req.url.length - '?allow=true'.length)) {
allowInvalid = true;
original = req.url.substring(5, req.url.length - '?allow=true'.length);
} else {
original = req.url.substr(5);
}
data = {
original_url: original
};
try { // I'm codifying the index in base 36 to reduce space
var baseUrl = (
(req.connection.encrypted ||
req.headers['x-forwarded-proto'] === 'https') ? "https" : "http") +
'://' + req.headers.host + '/';
data.short_url = baseUrl +
shortenerdb.addUrl(original, allowInvalid).toString(36);
} catch (e) {
data = {
error: "URL invalid"
};
} finally {
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(data), 'utf-8');
}
} else { // url retrival
//check if the parameter is a valid shortened URL
try {
var url = shortenerdb.getUrl(parseInt(req.url.substr(1), 36));
res.writeHead(302, {
'Location': url
});
res.end();
} catch (e) {
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
error: "No short url found for given input"
}), 'utf-8');
}
}
});
server.listen((process.env.PORT || 5000), function() {
console.log("Server URL Shortener listening on port: %s", (process.env.PORT || 5000));
});