-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathjsgi-node.js
255 lines (231 loc) · 5.47 KB
/
jsgi-node.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/*
JSGI 0.3 Adapter for Node
To use provide a JSGI application (can be application stack) to the start
function:
require("jsgi-node").start(function(request){
return request.body.join().then(function(requestBody){
return {
status:200,
headers:{},
body:["echo: " + requestBody]
};
});
});
This adapter should conform to the JSGI 0.3 (with promises) for full
asynchronous support. For example:
var fs = require("promised-io/fs");
require("jsgi-node").start(function(request){
return fs.readFile("jsgi-node.js").then(function(body){
return {
status: 200,
headers: {},
body: [body]
};
});
});
*/
var
sys = require( "sys" ),
url = require( "url" ),
defer = require("./promise").defer;
function Request( request ) {
var url = request.url;
var questionIndex = url.indexOf("?");
this.method = request.method;
this.nodeRequest = request;
this.headers = request.headers;
if(questionIndex > -1){
this.pathInfo = url.substring(0, questionIndex);
this.queryString = url.substring(questionIndex + 1);
}
else{
this.pathInfo = url;
this.queryString = "";
}
if(this.method != "GET"){ // optimize GET
this.body = new Input( request );
}
}
Request.prototype = {
jsgi:{
version: [ 0, 3 ],
multithread: false,
multiprocess: true,
async: true,
runOnce: false,
errors: {
print: sys.puts,
flush: function(){}
}
},
get env(){
return this._env || (this._env = {});
},
scriptName: "",
scheme:"http",
get host(){
var host = this.headers.host;
return host ? host.split(":")[0] : "";
},
get port(){
var host = this.headers.host;
return host ? (host.split(":")[1] || 80) : 80;
},
get remoteAddr(){
return this.nodeRequest.connection.remoteAddress;
},
get version(){
return [ this.nodeRequest.httpVersionMajor, this.nodeRequest.httpVersionMinor ]
}
};
function Input( request ) {
var
inputBuffer = [],
waitingForLength = Infinity;
function callback(data){
inputBuffer.push(data);
}
var deferred = defer();
request
.addListener( "data", function( data ) {
callback(data);
})
.addListener( "end", function() {
deferred.resolve();
});
this.forEach = function (each) {
if (this.encoding) {
request.setBodyEncoding( this.encoding );
}
inputBuffer.forEach(each);
callback = each;
return deferred.promise;
};
}
Input.prototype.join = function(token){
var parts = [];
return this.forEach(function(part){
parts.push(part);
}).then(function(){
return parts.join(token || ""); // yeah, I know Array.prototype.join defaults to ",", but clearly "" is more useful here
});
}
function Response( response, stream ) {
var started = false, canceller, cancel;
return handle;
function handle( data, notDone ) {
var forEachResult;
if ( typeof data.then === "function" ) {
if(!canceller){
stream.removeAllListeners("close");
canceller = function(){
stream.removeListener("close", canceller);
cancel && cancel();
}
stream.addListener("close", canceller);
}
cancel = data.cancel;
data.then(
handle,
function( error ) {
sys.puts("Error: " + error.stack);
handle({ status:500, headers:{}, body:[error.message] });
},
function( data ){
handle( data, true);
}
);
return;
}
if ( !started ) {
started = true;
response.writeHead( data.status || 500, data.headers );
}
try {
if ( typeof data.body === "string" ) {
response.write(data.body);
}
else if ( typeof data.body.forEach !== "function" ) {
throw new Error("The body does not have a forEach function");
}
else {
forEachResult = data.body.forEach( function( chunk ) {
try{
response.write( chunk, data.body.encoding || "utf8" );
}catch(e){
sys.puts( "error writing " + chunk + e);
}
});
}
if ( !notDone && forEachResult && ( typeof forEachResult.then === "function" ) ) {
cancel = forEachResult.cancel;
forEachResult.then( function() {
if(canceller){
stream.addListener("close", canceller);
}
response.end();
});
}
else if ( !notDone ) {
if(canceller){
stream.addListener("close", canceller);
}
response.end();
}
}
catch( e ) {
if(canceller){
stream.addListener("close", canceller);
}
try{
// if it is not too late, set the status
if(!response.statusCode){
response.writeHead(500, {});
}
}catch(e2){}
try{
response.write( "Error: " + e.stack );
response.end();
console.log("error",e);
}catch(e3){
sys.puts(e3.stack);
}
}
}
}
function Listener( app ) {
if(typeof app != "function"){
throw new Error("app must be a function");
}
return function( request, response ) {
var connection = request.connection;
request = new Request( request );
var respond = new Response( response, connection );
process.nextTick(function(){
var jsgiResponse;
try {
jsgiResponse = app( request )
} catch( error ) {
jsgiResponse = { status:500, headers:{}, body:[error.stack] };
}
respond( jsgiResponse );
});
}
}
start.Request = Request;
start.Listener = Listener;
start.start = start;
function start( app, options ) {
app = new Listener( app );
options = options || {};
var port = options.port || 8080,
http;
if ( options.ssl ) {
http = require( "https" ).createServer( options.ssl, app ).listen( port );
} else {
http = require( "http" ).createServer( app ).listen( port );
}
sys.puts( "Server running on port " + port );
return http;
};
module.exports = start;