| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- var fs = require('fs');
- function Url(url) {
- this.url = url;
- if (this.url.indexOf('?') >= 0)
- this.url = this.url.substr(0, this.url.indexOf('?'));
- while (this.url.length && this.url[0] === '/') {
- this.url = this.url.substr(1);
- }
- var urlParts = this.url.split("/");
- this.urlParts = [];
- for (var i =0, nbParts = urlParts.length; i < nbParts; i++) {
- if (urlParts[i])
- this.urlParts.push(urlParts[i]);
- }
- var stop = url.indexOf("?");
- if (stop === -1) {
- stop = url.length;
- }
- this.path = url.substr(0, stop);
- var queryTokens = url.substr(stop +1).split("&");
- this.queryTokens = {};
- for (var i =0, nbTokens = queryTokens.length; i < nbTokens; i++) {
- var token = queryTokens[i].split("=");
- if (token[0] !== "") {
- if (!this.queryTokens[token[0]]) {
- this.queryTokens[token[0]] = [];
- }
- this.queryTokens[token[0]].push(token[1] || true);
- }
- }
- this.serve = null;
- this.template = null;
- if (!tryLoadTemplate.apply(this))
- tryLoadPublic.apply(this);
- }
- function tryLoadPublic() {
- try{
- if (!this.urlParts.length) {
- this.serve = {
- filename: "public/index.html"
- ,stat: fs.statSync("public/index.html")
- };
- } else if (this.urlParts.length == 1) {
- this.serve = {
- filename: "public/" +this.urlParts[0]
- ,stat: fs.statSync("public/" +this.urlParts[0])
- };
- }
- return true;
- } catch (e) {
- // Not a public/ file
- }
- return false;
- }
- function tryLoadTemplateFile(fileName) {
- try{
- fs.statSync(fileName);
- } catch (e) {
- // Not a template file
- return null;
- }
- return require(fileName);
- }
- function tryLoadTemplate() {
- var template;
- if (!this.urlParts[0]) {
- template = tryLoadTemplateFile(__dirname +'/../template/index.js');
- } else if (this.urlParts[0][0] !== '_') {
- template = tryLoadTemplateFile(__dirname +'/../template/' +this.urlParts[0] +'.js');
- }
- if (!template || (template.match && !template.match(this)) || (!template.match && this.urlParts[0].length > 1)) {
- return false;
- }
- this.template = template;
- return true;
- }
- Url.prototype.isPublic = function() {
- return this.serve !== null;
- };
- Url.prototype.isTemplate = function() {
- return !!this.template;
- };
- Url.prototype.getReadStream = function() {
- return fs.createReadStream(this.serve.filename);
- };
- Url.prototype.match = function(arr) {
- if (arr.length !== this.urlParts.length)
- return false;
- for (var i=0, arrLen = arr.length; i < arrLen; i++)
- if (arr[i] !== this.urlParts[i] && arr[i] !== '?')
- return false;
- return true;
- }
- module.exports = { Url: Url };
|