Skip to content

Instantly share code, notes, and snippets.

@FiveYellowMice
Last active February 21, 2016 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FiveYellowMice/eec2123aeaf71327fa99 to your computer and use it in GitHub Desktop.
Save FiveYellowMice/eec2123aeaf71327fa99 to your computer and use it in GitHub Desktop.
https://fivy.ml USED TO powered by
#!/usr/bin/env node
const http = require("http");
const url = require("url");
const fs = require("fs");
const yaml = require("js-yaml");
var server = http.createServer(recievedRequest);
server.listen(8063, "::1", function() {
console.log("Start serving...");
});
var database;
rereadData();
process.on("SIGHUP", rereadData);
var websiteRoot = "https://fiveyellowmice.github.io";
function rereadData() {
fs.readFile(__dirname + "/urls.yaml", "utf-8", function(error, file) {
if (error) throw error;
database = yaml.safeLoad(file);
console.log("Database read");
});
}
function recievedRequest(request, response) {
var sourceIp;
try {
sourceIp = request.headers["x-forwarded-for"] || request.connection.remoteAddress || request.socket.remoteAddress || request.connection.socket.remoteAddress;
} catch (error) {
sourceIp = "unknown";
}
console.log("Request: " + request.method + " " + request.url + "\t" + sourceIp);
var pathname = url.parse(request.url).pathname;
if (pathname === "/") {
response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
var table = "";
for (var name in database) {
if (database.hasOwnProperty(name)) {
table += "<tr><td><a href=\"" + websiteRoot + database[name] + "\">" + name + "</a></td><td>" + database[name] + "</td></tr>";
}
}
response.write("<html><head><meta charset=\"utf-8\" /><meta name=\"robots\" content=\"noindex\" /><title>FiveYellowMice's Short URL</title></head><body>" +
"<h1>FiveYellowMice's Short URL</h1>" +
"<p>这里的短链接是为 FiveYellowMice's Blog 准备的。如果你需要生成短链接,可别找我。</p>" +
"<table>" + table + "</table>" +
"</body></html>"
);
response.end();
return;
}
if (!database.hasOwnProperty(pathname.substring(1))) {
response.writeHead(404);
response.end("Not found.");
return;
}
var location = websiteRoot + database[pathname.substring(1)];
response.writeHead(301, { location: location });
response.end("<html><head></head><body><p>Redirecting to <a href=\"" + location + "\">here</a>.</p></body></html>");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment