|
|
@@ -0,0 +1,93 @@
|
|
|
+
|
|
|
+const http = require('http')
|
|
|
+ ,fs = require('fs');
|
|
|
+
|
|
|
+function HttpServer(config) {
|
|
|
+ var ctx = this;
|
|
|
+
|
|
|
+ this.config = config;
|
|
|
+ this.httpServ = http.createServer(function(req, res) {
|
|
|
+ req.reqT = new Date();
|
|
|
+ res.ended = false;
|
|
|
+ res.once('end', () => {
|
|
|
+ res.ended = true;
|
|
|
+ });
|
|
|
+ if (ctx.isRequestPublic(req.url)) {
|
|
|
+ try {
|
|
|
+ ctx.servePublic(req.url, res);
|
|
|
+ } catch (e) {
|
|
|
+ if (e instanceof HttpServer.Error404) {
|
|
|
+ res.writeHeader("404", "Not found");
|
|
|
+ ctx.servePublic("/404.html", res);
|
|
|
+ } else {
|
|
|
+ console.error("Unknown error", e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ ctx.serveApi(req, res);
|
|
|
+ }
|
|
|
+ ctx.logRequest(req, res);
|
|
|
+ });
|
|
|
+};
|
|
|
+
|
|
|
+HttpServer.prototype.run = function() {
|
|
|
+ this.httpServ.listen(this.config.port, () => {
|
|
|
+ console.log("[http] listening on " +this.config.port);
|
|
|
+ });
|
|
|
+};
|
|
|
+
|
|
|
+HttpServer.prototype.logRequest = function(req, res) {
|
|
|
+ console.log("[http] "
|
|
|
+ +req.reqT.toISOString()
|
|
|
+ +" "
|
|
|
+ +req.socket.remoteAddress
|
|
|
+ +" "
|
|
|
+ +res.statusCode);
|
|
|
+};
|
|
|
+
|
|
|
+HttpServer.prototype.isRequestPublic = function(url) {
|
|
|
+ return url.indexOf("/api/") === -1;
|
|
|
+};
|
|
|
+
|
|
|
+HttpServer.prototype.servePublic = function(url, res) {
|
|
|
+ var pathTokens = url.split('/')
|
|
|
+ ,localPath = './public';
|
|
|
+
|
|
|
+ pathTokens.forEach(function(i) {
|
|
|
+ i = i.trim();
|
|
|
+ if (i != '' && i[0] != '.') {
|
|
|
+ localPath += '/' +i;
|
|
|
+ }
|
|
|
+ });
|
|
|
+ var stat;
|
|
|
+ try {
|
|
|
+ var stat = fs.lstatSync(localPath);
|
|
|
+ if (stat.isDirectory()) {
|
|
|
+ localPath += "/index.html";
|
|
|
+ stat = fs.lstatSync(localPath);
|
|
|
+ }
|
|
|
+ } catch (e) {
|
|
|
+ throw new HttpServer.Error404(localPath);
|
|
|
+ }
|
|
|
+ if (!res.headersSent) {
|
|
|
+ if (!this.config.isDebug) {
|
|
|
+ res.setHeader("Cache-Control", "private, max-age=900");
|
|
|
+ }
|
|
|
+ res.setHeader("Content-Length", stat.size);
|
|
|
+ }
|
|
|
+ fs.createReadStream(localPath).pipe(res, { end: true });
|
|
|
+};
|
|
|
+
|
|
|
+HttpServer.prototype.serveApi = function(req, res) {
|
|
|
+ res.end("Coucou");
|
|
|
+};
|
|
|
+
|
|
|
+HttpServer.Error404 = function(localPath) {
|
|
|
+ console.log("[http] file not found: " +localPath);
|
|
|
+};
|
|
|
+
|
|
|
+module.exports.serve = function(config) {
|
|
|
+ var server = new HttpServer(config);
|
|
|
+ server.run();
|
|
|
+};
|
|
|
+
|