-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathshort.js
54 lines (49 loc) · 1.29 KB
/
short.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
var url = require('url'),
express = require('express'),
short = require('short'),
app = express.createServer(),
port = process.env.PORT || 8080,
domain = "http://192.168.1.111";
short.connect("mongodb://localhost/short");
app.get('/api/*', function (req, res) {
if (req.url === '/favicon.ico') {
return;
}
var removeApi = req.url.slice(5),
URL = removeApi,
options = {length: 7};
short.generate(URL, options, function (error, shortURL) {
if (error) {
console.error(error);
}
else {
var tinyUrl = [domain, ":", port, "/", shortURL.hash].join("");
console.log(["URL is ", shortURL.URL, " ", tinyUrl].join(""));
res.end(tinyUrl);
}
});
});
app.get('*', function (req, res) {
if (req.url === '/favicon.ico') {
return;
}
var visitor = req.connection.remoteAddress,
hash = req.url.slice(1),
options = {visitor: visitor};
short.retrieve(hash, options, function (error, shortURLObject) {
if (error) {console.error(error);
} else {
if (shortURLObject) {
res.redirect(shortURLObject.URL, 302);
}
else {
res.send('URL not found!', 404);
res.end();
}
}
});
});
app.listen(port, function () {
console.log('Server running on port ' + port);
});
/* EOF */