-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy paththtp.class.js
108 lines (91 loc) · 2.74 KB
/
thtp.class.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
var http = require('http');
var util = require('util');
var lob = require("lob-enc");
var stream = require('stream');
var ChannelStream = require("./stream.class");
var THTP = {
Request : {
//fromHTTP : THTP_Request_fromHTTP,
toHTTP : THTP_Request_toHTTP
},
Response : {
fromHTTP : THTP_Response_fromHTTP
//toHTTP : THTP_Response_toHTTP
}
};
module.exports = THTP;
var RequestSuper = (http.IncomingMessage) || stream.Readable;
var ResponseSuper = (http.ServerResponse) || stream.Writable;
util.inherits(THTP_Request_toHTTP, RequestSuper);
util.inherits(THTP_Response_fromHTTP, ResponseSuper);
function THTP_Request_toHTTP(packet,link, stream){
// mimic http://nodejs.org/api/http.html#http_http_incomingmessage
http.IncomingMessage.call(this);
this.method = packet.json[':method'];
this.url = packet.json[':path'] || "/";
this.headers = packet.json;
this.headers['x-hashname'] = link.hashname; // for any http handler visibility
this.hashname = link.hashname;
this.connection = {
remoteAddress : link.hashname
, cork : function(){
//noop
}
};
this.on = stream.on.bind(stream);
this.read = stream.read.bind(stream);
this.pipe = stream.pipe.bind(stream);
}
function THTP_Response_fromHTTP(req, link, stream){
// mimic http://nodejs.org/api/http.html#http_http_incomingmessage
http.ServerResponse.call(this, req);
this.connection = {
remoteAddress : link.hashname,
_httpMessage : this,
cork : function(){
//console.log('res cork')
}, uncork : function(){
//console.log("uncork")
}
};
var head = false;
//this.on = stream.on.bind(stream)
this._writeRaw = stream._write.bind(stream);
this._write = stream._write.bind(stream);
this.on('pipe',function(from){
from.on('end',stream.end.bind(stream));
});
this.end = function THTP_RES_End(data, enc, callback){
if (!head)
this.writeHead(200);
stream.end(data)
};
this.writeHead = function THTP_writeHead(statusCode, reasonPhrase, headers)
{
// don't double!
this._header = ""
if(head){
//console.log('double call to thtp writeHead',this.statusCode,(new Error()).stack)
return this;
};
head = true;
// be friendly
if(!headers && typeof reasonPhrase == 'object'){
headers = reasonPhrase;
reasonPhrase = false;
} else if (!headers ){
headers = this._headers;
}
this.statusCode = parseInt(statusCode) || 500;
var json = {};
json[':status'] = this.statusCode;
if(reasonPhrase)
json[':reason'] = reasonPhrase;
if(headers)
Object.keys(headers).forEach(function ForEachHeader(header){
json[header.toLowerCase()] = headers[header];
});
stream.write(lob.encode(json,false));
return this;
};
}