UNPKG

1.39 kBJavaScriptView Raw
1'use strict';
2
3var utils = require('./../utils');
4
5// Headers whose duplicates are ignored by node
6// c.f. https://nodejs.org/api/http.html#http_message_headers
7var ignoreDuplicateOf = [
8 'age', 'authorization', 'content-length', 'content-type', 'etag',
9 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
10 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
11 'referer', 'retry-after', 'user-agent'
12];
13
14/**
15 * Parse headers into an object
16 *
17 * ```
18 * Date: Wed, 27 Aug 2014 08:58:49 GMT
19 * Content-Type: application/json
20 * Connection: keep-alive
21 * Transfer-Encoding: chunked
22 * ```
23 *
24 * @param {String} headers Headers needing to be parsed
25 * @returns {Object} Headers parsed into an object
26 */
27module.exports = function parseHeaders(headers) {
28 var parsed = {};
29 var key;
30 var val;
31 var i;
32
33 if (!headers) { return parsed; }
34
35 utils.forEach(headers.split('\n'), function parser(line) {
36 i = line.indexOf(':');
37 key = utils.trim(line.substr(0, i)).toLowerCase();
38 val = utils.trim(line.substr(i + 1));
39
40 if (key) {
41 if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
42 return;
43 }
44 if (key === 'set-cookie') {
45 parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
46 } else {
47 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
48 }
49 }
50 });
51
52 return parsed;
53};