http_parser.js
2.44 KB
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
'use strict';
var NodeHTTPParser = process.binding('http_parser').HTTPParser,
version = NodeHTTPParser.RESPONSE ? 6 : 4;
var HttpParser = function(type) {
if (type === 'request')
this._parser = new NodeHTTPParser(NodeHTTPParser.REQUEST || 'request');
else
this._parser = new NodeHTTPParser(NodeHTTPParser.RESPONSE || 'response');
this._type = type;
this._complete = false;
this.headers = {};
var current = null,
self = this;
this._parser.onHeaderField = function(b, start, length) {
current = b.toString('utf8', start, start + length).toLowerCase();
};
this._parser.onHeaderValue = function(b, start, length) {
var value = b.toString('utf8', start, start + length);
if (self.headers.hasOwnProperty(current))
self.headers[current] += ', ' + value;
else
self.headers[current] = value;
};
this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] =
function(majorVersion, minorVersion, headers, method, pathname, statusCode) {
var info = arguments[0];
if (typeof info === 'object') {
method = info.method;
pathname = info.url;
statusCode = info.statusCode;
headers = info.headers;
}
self.method = (typeof method === 'number') ? HttpParser.METHODS[method] : method;
self.statusCode = statusCode;
self.url = pathname;
if (!headers) return;
for (var i = 0, n = headers.length, key, value; i < n; i += 2) {
key = headers[i].toLowerCase();
value = headers[i+1];
if (self.headers.hasOwnProperty(key))
self.headers[key] += ', ' + value;
else
self.headers[key] = value;
}
self._complete = true;
};
};
HttpParser.METHODS = {
0: 'DELETE',
1: 'GET',
2: 'HEAD',
3: 'POST',
4: 'PUT',
5: 'CONNECT',
6: 'OPTIONS',
7: 'TRACE',
8: 'COPY',
9: 'LOCK',
10: 'MKCOL',
11: 'MOVE',
12: 'PROPFIND',
13: 'PROPPATCH',
14: 'SEARCH',
15: 'UNLOCK',
16: 'REPORT',
17: 'MKACTIVITY',
18: 'CHECKOUT',
19: 'MERGE',
24: 'PATCH'
};
HttpParser.prototype.isComplete = function() {
return this._complete;
};
HttpParser.prototype.parse = function(chunk) {
var offset = (version < 6) ? 1 : 0,
consumed = this._parser.execute(chunk, 0, chunk.length) + offset;
if (this._complete)
this.body = (consumed < chunk.length)
? chunk.slice(consumed)
: new Buffer(0);
};
module.exports = HttpParser;