-
Notifications
You must be signed in to change notification settings - Fork 1
/
unmon.js
170 lines (138 loc) · 4.9 KB
/
unmon.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
var http=require("http");
var unmon={};
/* Your default stack */
var routes=unmon.routes=[];
var debug=unmon.debug=true;
var plugin=unmon.plugin=function(name){
var mod;
if(unmon.debug){
console.log("Loading %s plugin",name);
}
try{
mod=require("./lib/"+name);
}catch(err){
if(unmon.debug){
console.error("Error loading %s",name);
console.error(err);
}
}
return mod;
};
/* route produces new routes, and pushes them to a stack */
var route=unmon.route=function(patt,f,opts){
opts=opts||{}; // you don't have to provide options
// make sure the discriminator is defined
opts.disc=opts.disc||'url'; // your router parses by url by default
opts.stack=opts.stack||routes; // you can provide an alternate stack
if(typeof f !== 'function'){
console.error("[ROUTE ERROR]: Second argument provided to unmon.route (%s) is not a function. ignoring...\n",f);
return;
}
if(typeof patt === 'string'){
if(unmon.debug){
console.log("[ROUTE DEBUG]: Got a string instead of a regular expression.\n...Attempting to convert");
}
patt=patt
// support 'globbing'
.replace(/\*/g,function(esc){
return '.'+esc;
})
// escape relevant characters, I'm sure this is incomplete.
.replace(/[\\\/\-\+\?\{\}\(\)\[\]\^\$\.]/g,function(esc){
return '\\'+esc;
});
if(unmon.debug){
console.log("[ROUTE DEBUG]: Route expression is %s",patt);
}
patt=new RegExp(patt);
}
// push your new route to the stack in question
opts.stack.push(function(req,res,Next){
if(typeof Next !== 'function'){
Next=function(req,res){
res.statusCode=404;
res.end('404');
};
}
// encapsulate Next so that we don't always have to pass req and res
var next=function(){Next(req,res);};
if(patt.test(req[opts.disc])){
f(req,res,next);
}else{
next();
}
});
};
/* makeRouter accepts a stack of routes and collapses it into a single function
which is compatible with the NodeJS http api
of the form function(request,response) */
var makeRouter=unmon.makeRouter=function(stack){
stack=stack||unmon.routes;
return stack.reduceRight(function(b,a,i,z){
return function(req,res){
a(req,res,b);
};
},[]);
};
var createServer=unmon.createServer=function(callback){
callback=callback||makeRouter();
return http.createServer(callback);
};
/* If being run as a standalone server, load routes and launch a server */
if(require.main === module){
// Running unmon as standalone script
var __dirname=process.argv[1].replace(/\/[^\/]*$/,'');
console.log(__dirname);
/* instantiate error logging behaviour
this catches ALL uncaught exceptions
which is possibly a security risk if your server SHOULD crash */
global.logError=plugin('error')();
/* This is where you add your routes */
/* infer appropriate caching behaviour from requested urls */
route(/.*/,plugin('cache')());
/* Enable CORS headers for api access */
route(/.*/,plugin('cors')());
/* Log all requests to file */
route(/.*/,plugin('logger')({path:process.env.PWD+'/log/'}));
/* Process post requests and export them as req.postdata */
route(/.*/,plugin('posted')());
/* Templating and serverside scripting */
route(/.*/,plugin('koan')({
error:logError
}));
/* find and serve static files */
route(/.*/,plugin('fixed')({
path:__dirname+'/static'
}));
route(/\/shared\/.*/,plugin('directive')({
path:__dirname+'/static/'
}));
/* load the blag plugin for serving templated markdown files */
route(/.*/,plugin('blag')({path:process.env.PWD+"/md/",title:" "}));
/* 404 as a last resort */
route(/.*/,plugin('parcel')(process.env.PWD+"/static/html/404.html"));
// produce a new router
var router=makeRouter(routes)
// make the port known globally for other scripts
global.thisServersPort=8083;
// bind to all ipv4 addresses by default
var addresses=[''];
// check if you have a unique local ipv6 address
(function(){
global.thisServersIPV6=plugin('fc')();
if(thisServersIPV6)
addresses.push(thisServersIPV6[0]);
})();
// instantiate and launch a server for each address in addresses
var servers=addresses.map(function(addy){
var server=http.createServer(router);
server.listen(thisServersPort,addy,function(){
console.log("unmon is running on %s:%s",addy,thisServersPort);
});
return server;
});
}else{
/* If this module is being loaded as a library by another file
just export the router functions */
module.exports=unmon;
}