Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

secure server supports.

  • Loading branch information...
commit 43f0e5569c867eae8b4ffc8537efa94622b4fa60 1 parent 8f970a2
@JacksonTian authored
View
93 asset.js
@@ -0,0 +1,93 @@
+var url = require("url");
+var fs = require("fs");
+var path = require("path");
+var mime = require("./mime").types;
+var config = require("./config");
+var utils = require("./utils");
+var zlib = require("zlib");
+
+var Asset = function () {};
+
+Asset.prototype.dispatch = function (request, response) {
+ response.setHeader("Server", "Node/V5");
+ response.setHeader('Accept-Ranges', 'bytes');
+ var pathname = url.parse(request.url).pathname;
+ if (pathname.slice(-1) === "/") {
+ pathname = pathname + config.Welcome.file;
+ }
+ var realPath = path.join("assets", path.normalize(pathname.replace(/\.\./g, "")));
+
+ var pathHandle = function (realPath) {
+ fs.stat(realPath, function (err, stats) {
+ if (err) {
+ response.writeHead(404, "Not Found", {'Content-Type': 'text/plain'});
+ response.write("This request URL " + pathname + " was not found on this server.");
+ response.end();
+ } else {
+ if (stats.isDirectory()) {
+ realPath = path.join(realPath, "/", config.Welcome.file);
+ pathHandle(realPath);
+ } else {
+ var ext = path.extname(realPath);
+ ext = ext ? ext.slice(1) : 'unknown';
+ var contentType = mime[ext] || "text/plain";
+ response.setHeader("Content-Type", contentType);
+ response.setHeader('Content-Length', stats.size);
+
+ var lastModified = stats.mtime.toUTCString();
+ var ifModifiedSince = "If-Modified-Since".toLowerCase();
+ response.setHeader("Last-Modified", lastModified);
+
+ if (ext.match(config.Expires.fileMatch)) {
+ var expires = new Date();
+ expires.setTime(expires.getTime() + config.Expires.maxAge * 1000);
+ response.setHeader("Expires", expires.toUTCString());
+ response.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge);
+ }
+
+ if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) {
+ response.writeHead(304, "Not Modified");
+ response.end();
+ } else {
+ var compressHandle = function (raw, statusCode, reasonPhrase) {
+ var stream = raw;
+ var acceptEncoding = request.headers['accept-encoding'] || "";
+ var matched = ext.match(config.Compress.match);
+
+ if (matched && acceptEncoding.match(/\bgzip\b/)) {
+ response.setHeader("Content-Encoding", "gzip");
+ stream = raw.pipe(zlib.createGzip());
+ } else if (matched && acceptEncoding.match(/\bdeflate\b/)) {
+ response.setHeader("Content-Encoding", "deflate");
+ stream = raw.pipe(zlib.createDeflate());
+ }
+ response.writeHead(statusCode, reasonPhrase);
+ stream.pipe(response);
+ };
+
+ if (request.headers["range"]) {
+ var range = utils.parseRange(request.headers["range"], stats.size);
+ if (range) {
+ response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + stats.size);
+ response.setHeader("Content-Length", (range.end - range.start + 1));
+ var raw = fs.createReadStream(realPath, {"start": range.start, "end": range.end});
+ compressHandle(raw, 206, "Partial Content");
+ } else {
+ response.removeHeader("Content-Length");
+ response.writeHead(416, "Request Range Not Satisfiable");
+ response.end();
+ }
+ } else {
+ var raw = fs.createReadStream(realPath);
+ compressHandle(raw, 200, "Ok");
+ }
+ }
+ }
+ }
+ });
+ };
+
+ pathHandle(realPath);
+};
+
+exports.Asset = Asset;
View
12 certs/ping-csr.pem
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIIB1TCCAT4CAQAwfjELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFNoYW5naGFpMREw
+DwYDVQQHDAhTaGFuZ2hhaTEOMAwGA1UECgwFQ05vZGUxFTATBgNVBAMMDEphY2tz
+b24gVGlhbjEiMCAGCSqGSIb3DQEJARYTc2h5dm8xOTg3QGdtYWlsLmNvbTCBnzAN
+BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0mGIYebaRufKjh5sPbeAMi2Y8kuDUfsk
+ue7KWdnjQd7ZPsUXEhDaN8uljXuHqMCE9cotjGoMK1uwlIsCiFrzv4zj03VABrkc
+YHBIBW9LW7kssNfzM3Qs4smvqBwJ2+zVUN8itFf1PFGwEpyLV+JB6rO25q7Wbkq6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u+2U+ZlO5/7OkCQDmCHHoZy2b2DUaweOdqNIkyqcNLAadJDlcZvN35tvj0
+bPRvezY2G7LTcg9j/9jhEMGi9ELEQDzYvwIsNKXO2qk=
+-----END RSA PRIVATE KEY-----
View
3  config.js
@@ -8,4 +8,5 @@ exports.Compress = {
exports.Welcome = {
file: "index.html"
};
-exports.Timeout = 20 * 60 * 1000;
+exports.Timeout = 20 * 60 * 1000;
+exports.Secure = null;
View
76 context.js
@@ -0,0 +1,76 @@
+var path = require("path");
+var fs = require("fs");
+var footprint = require("./footprint");
+
+var Context = function (request, response, session, framework) {
+ this.request = request;
+ this.response = response;
+ this.session = session;
+ this.framework = framework;
+};
+Context.prototype.none = function () {
+ this.response.writeHead(204);
+ this.response.end();
+};
+Context.prototype.renderJSON = function (jsonObj) {
+ this.response.setHeader("Content-Type", "application/json");
+ this.response.writeHead(200);
+ this.response.end(JSON.stringify(jsonObj));
+};
+Context.prototype.redirect = function (url) {
+ this.response.setHeader("Location", url);
+ this.response.writeHead(301);
+ this.response.end();
+};
+Context.prototype._renderView = function (viewEngine, template, data) {
+ var framework = this.framework,
+ request = this.request,
+ response = this.response;
+
+ try {
+ response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
+ response.write(viewEngine.template(template, data));
+ response.end();
+ } catch (ex) {
+ console.log(ex.message);
+ console.log(ex.stack);
+ framework.handler500(request, response, "Parse template error.");
+ }
+};
+
+Context.prototype.renderView = function (view, data) {
+ var context = this,
+ framework = context.framework,
+ request = context.request,
+ response = context.response;
+
+ // Get engine.
+ var viewEngine = footprint;
+
+ // Check cache.
+ viewEngine._cache = viewEngine._cache || {};
+ var template = viewEngine._cache[view];
+ if (template) {
+ context._renderView(viewEngine, template, data);
+ } else {
+ var filePath = path.join(__dirname, "views/", view);
+
+ path.exists(filePath, function (exists) {
+ if(!exists) {
+ framework.handler500(request, response, "This template file doesn't exist.");
+ } else {
+ fs.readFile(filePath, "utf8", function(err, file) {
+ if (err) {
+ framework.handler500(request, response, err);
+ } else {
+ viewEngine._cache[view] = file;
+ context._renderView(viewEngine, file, data);
+ }
+ });
+ }
+ });
+ }
+};
+Context.prototype.renderPartial = Context.prototype.renderView;
+
+exports.Context = Context;
View
96 framework.js
@@ -3,85 +3,20 @@ var url = require("url");
var cookie = require("./cookie");
var session = require("./session");
var config = require("./config");
-var footprint = require("./footprint");
var path = require("path");
-var fs = require("fs");
+var Context = require("./context").Context;
-var Context = function (request, response, session, framework) {
- this.request = request;
- this.response = response;
- this.session = session;
- this.framework = framework;
-};
-Context.prototype.none = function () {
- this.response.writeHead(204);
- this.response.end();
-};
-Context.prototype.renderJSON = function (jsonObj) {
- this.response.setHeader("Content-Type", "application/json");
- this.response.writeHead(200);
- this.response.end(JSON.stringify(jsonObj));
-};
-Context.prototype.redirect = function (url) {
- this.response.setHeader("Location", url);
- this.response.writeHead(301);
- this.response.end();
+var Framework = function () {
+ this.sessionManager = new session.SessionManager(config.Timeout);
};
-Context.prototype._renderView = function (viewEngine, template, data) {
- var framework = this.framework,
- request = this.request,
- response = this.response;
- try {
- response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
- response.write(viewEngine.template(template, data));
+Framework.prototype.dispatch = function (request, response) {
+ if (request.url == "/favicon.ico") {
+ response.writeHead(404, "Not Found");
response.end();
- } catch (ex) {
- console.log(ex.message);
- console.log(ex.stack);
- framework.handler500(request, response, "Parse template error.");
- }
-};
-
-Context.prototype.renderView = function (view, data) {
- var context = this,
- framework = context.framework,
- request = context.request,
- response = context.response;
-
- // Get engine.
- var viewEngine = footprint;
-
- // Check cache.
- viewEngine._cache = viewEngine._cache || {};
- var template = viewEngine._cache[view];
- if (template) {
- context._renderView(viewEngine, template, data);
- } else {
- var filePath = path.join(__dirname, "views/", view);
-
- path.exists(filePath, function (exists) {
- if(!exists) {
- framework.handler500(request, response, "This template file doesn't exist.");
- } else {
- fs.readFile(filePath, "utf8", function(err, file) {
- if (err) {
- framework.handler500(request, response, err);
- } else {
- viewEngine._cache[view] = file;
- context._renderView(viewEngine, file, data);
- }
- });
- }
- });
+ return;
}
-};
-Context.prototype.renderPartial = Context.prototype.renderView;
-var Framework = function () {
- this.sessionManager = new session.SessionManager(config.Timeout);
-};
-Framework.prototype.dispatch = function (request, response) {
var routeInfo = this.route(request.url);
var controller;
try {
@@ -93,7 +28,8 @@ Framework.prototype.dispatch = function (request, response) {
this.enableCookie(request, response);
this.enablePost(request, response);
var curSession = this.enableSession(request, response);
- var context = new Context(request, response, curSession, framework);
+ // Pass request response session and framework into context object.
+ var context = new Context(request, response, curSession, this);
request.on("end", function () {
action.apply(context, routeInfo.args);
});
@@ -199,16 +135,4 @@ Framework.prototype.route = function (requestUrl) {
};
};
-var framework = new Framework();
-
-var server = http.createServer(function (request, response) {
- if (request.url == "/favicon.ico") {
- response.writeHead(404, "Not Found");
- response.end();
- return;
- }
- framework.dispatch(request, response);
-});
-
-server.listen(8000);
-console.log("Running at 8000 port.");
+exports.Framework = Framework;
View
13 ping.js
@@ -0,0 +1,13 @@
+var http = require("http");
+var https = require("https");
+var config = require("./config");
+
+exports.createServer = function (framework) {
+ var options = config.secure;
+ var server = options ? https.createServer(options) : http.createServer();
+ server.on("request", function (request, response) {
+ framework.dispatch(request, response);
+ });
+
+ return server;
+};
View
95 server.js
@@ -1,88 +1,15 @@
var http = require("http");
-var url = require("url");
-var qs = require("querystring");
-var cookie = require("./cookie");
-var session = require("./session");
-var config = require("./config");
+var ping = require("./ping");
+var Framework = require("./framework").Framework;
+var Asset = require("./asset").Asset;
-var sessionManager = new session.SessionManager(config.Timeout);
+// Dynamic handle.
+var framework = new Framework();
+ping.createServer(framework).listen(8000);
+console.log("Running at 8000 port.");
-var server = http.createServer(function (request, response) {
+// Static file server.
+var asset = new Asset();
+ping.createServer(asset).listen(8080);
- if (request.url == "/favicon.ico") {
- response.writeHead(404, "Not Found");
- response.end();
- return;
- }
- var handle = function (session) {
- response.setHeader("Content-Type", "text/plain");
- response.writeHead(200, "Ok");
- if (!session.get("username")) {
- session.set("username", request.get("username"));
- }
- response.write("Hi, " + session.get("username") + "\n\r");
- response.end();
- };
-
- var _cookieMap;
- request.cookie = function (key) {
- if (!_cookieMap) {
- _cookieMap = cookie.parse(request.headers.cookie || "");
- }
- return _cookieMap[key];
- };
- var _setCookieMap = {};
- response.setCookie = function (cookieObj) {
- _setCookieMap[cookieObj.key] = cookie.stringify(cookieObj);
- var returnVal = [];
- for(var key in _setCookieMap) {
- returnVal.push(_setCookieMap[key]);
- }
-
- response.setHeader("Set-Cookie", returnVal.join(", "));
- };
-
- var sessionId = request.cookie(session.SESSIONID_KEY);
- console.log(_cookieMap);
- var curSession;
- if (sessionId && (curSession = sessionManager.get(sessionId))) {
- if (sessionManager.isTimeout(curSession)) {
- sessionManager.remove(sessionId);
- curSession = sessionManager.renew(response);
- } else {
- curSession.updateTime();
- }
- } else {
- curSession = sessionManager.renew(response);
- }
-
- var _urlMap;
- request.get = function (key) {
- if (!_urlMap) {
- _urlMap = url.parse(request.url, true);
- }
- return _urlMap.query[key];
- };
- if (request.method === "POST") {
- var _postData = "",
- _postMap = "";
-
- request.on('data', function (chunk) {
- _postData += chunk;
- })
- .on("end", function () {
- request.postData = _postData;
- request.post = function (key) {
- if (!_postMap) {
- _postMap = qs.parse(_postData);
- }
- return _postMap[key];
- };
- handle(curSession);
- });
- } else {
- handle(curSession);
- }
-});
-
-server.listen(8000);
+console.log("Running at 8080 port.");
Please sign in to comment.
Something went wrong with that request. Please try again.