Parses CGI headers (\n newlines) until a blank line,
signifying the end of the headers. After the blank line
is assumed to be the body, which you can use 'pipe()' with.
500641
function Parser(stream) {
  StreamStack.call(this, stream, {
    data: function(b) { this._onData(b); }
  });
  this._onData = this._parseHeader;
  this._headerParser = new HeaderParser(new Stream(), {
    emitFirstLine: false,
    strictCRLF: false,
    strictSpaceAfterColon: false,
    allowFoldedHeaders: false
  });
  this._headerParser.on('headers', this._onHeadersComplete.bind(this));
}
79364
function parseHeaders() {
  var str = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];

  var lines = str.split(/\r?\n/);
  var fields = {};
  var index = undefined;
  var line = undefined;
  var field = undefined;
  var val = undefined;

  lines.pop(); // trailing CRLF

  for (var i = 0, len = lines.length; i < len; i += 1) {
    line = lines[i];
    index = line.indexOf(':');
    field = line.slice(0, index).toLowerCase();
    val = trim(line.slice(index + 1));
    fields[field] = val;
  }

  return fields;
}
548671
function processHeader($lastLine = "\r\n") {
      $headers = array();
      $finished = false;

      while ( (!$finished) && (!feof($this->socket)) ) {
        $str = fgets($this->socket, 1024);
        $finished = ($str == $lastLine);
        if (!$finished) {
          list($hdr, $value) = preg_split('/: /', $str, 2);
// nasty workaround broken multiple same headers (eg. Set-Cookie headers) @FIXME
          if (isset($headers[$hdr])) {
            $headers[$hdr] .= '; ' . trim($value);
          } else {
            $headers[$hdr] = trim($value);
          }
        }
      }

      return $headers;
    }
392152
function parseAwsIni(ini) {
  var section,
      out = Object.create(null),
      re = /^\[([^\]]+)\]\s*$|^([a-z_]+)\s*=\s*(.+?)\s*$/,
      lines = ini.split(/\r?\n/)

  lines.forEach(function(line) {
    var match = line.match(re)
    if (!match) return
    if (match[1]) {
      section = match[1]
      if (out[section] == null) out[section] = Object.create(null)
    } else if (section) {
      out[section][match[2]] = match[3]
    }
  })

  return out
}
200108
function (string) {
    if (!string || string === '' || string.indexOf('\r\n') === -1) {
      return {
        version: 'HTTP/1.1',
        statusText: ''
      }
    }

    var lines = string.split('\r\n')
    var status = lines.shift()

    // Remove empty strings
    lines = lines.filter(Boolean)

    // Parse status line
    var output = this.parseStartLine(status)

    // init headers object & array
    output.headersObj = {}
    output.headersArr = []

    // Parse headers
    var header
    for (var i = lines.length; i--;) {
      header = this.parseHeaderLine(lines[i])

      output.headersArr.push(header)
      output.headersObj[header.name] = header.value
    }

    return output
  }
677043
function parseAhead( router, req, done ) {
	var idx = 0;
	var stack = router.stack;
	var params = {};
	var method = req.method ? req.method.toLowerCase() : undefined;
	next();

	function next() {
		var layer = stack[ idx++ ];
		if ( !layer ) {
			// strip dangling query params
			params = _.transform( params, function( acc, v, k ) {
				acc[ k ] = v.split( '?' )[ 0 ]; return acc;
			}, {} );
			return done( params );
		}

		if ( layer.method && layer.method !== method ) {
			return next();
		}
		layer.match( req.originalUrl );
		params = _.merge( params, layer.params );
		next();
	}
}
1326951
function parse(headers) {
    var output = {}, i, p, k, v;
    headers = headers || '';
    headers = headers.replace('\r', '');
    headers = headers.split('\n');
    for(i = 0;i < headers.length;i++) {
      p = headers[i].indexOf(':');
      k = headers[i].substr(0, p);
      v = headers[i].substr(p + 1);
      if(k && v) {
        k = k.replace(/^\s+/, '').replace(/\s+$/, '');
        v = v.replace(/^\s+/, '').replace(/\s+$/, '');
        output[k.toLowerCase()] = v;
      }
    }
    return output;
  }
93737
public function parseHeader()
    {
        //$header = explode("\r\n", rtrim($this->response['headerRaw'], "\r\n"));
        
        $rawHeaders = rtrim($this->response['headerRaw'], "\r\n");
        # Handle multiple responses e.g. with redirections (proxies too)
        $headerGroups = explode("\r\n\r\n", $rawHeaders);
        # We're only interested in the last one
        $header = explode("\r\n", end($headerGroups));

        $output = array();

        if ('HTTP' === substr($header[0], 0, 4)) {
            list($output['version'], $output['status']) = explode(' ', $header[0]);
            unset($header[0]);
        }

        foreach ($header as $entry) {
            $pos = strpos($entry, ':');
            $output[trim(substr($entry, 0, $pos))] = trim(substr($entry, $pos + 1));
        }

        $this->response['header'] = $output;
        return $this;
    }
1168094
public function parseBody( $origLine )
    {
        if ( $this->parserState == self::PARSE_STATE_POST_LAST )
        {
            return;
        }

        $line = rtrim( $origLine, "\r\n" );

        // check if we hit any of the boundaries
        $newPart = false;
        $endOfMultipart = false;
        if ( strlen( $line ) > 0 && $line[0] == "-" )
        {
            if ( strcmp( trim( $line ), '--' . $this->boundary ) === 0 )
            {
                $newPart = true;
            }
            else if ( strcmp( trim( $line ), '--' . $this->boundary . '--' ) === 0 )
            {
                $endOfMultipart = true;
            }
        }

        // actions to do when starting or finishing a part
        if ( $newPart || $endOfMultipart )
        {
            if ( $this->parserState != self::PARSE_STATE_BODY )
            {
                // something is b0rked, we got a new separator before getting a body
                // we'll skip this part and continue to the next
                $this->currentPartParser = null;
                $this->currentPartHeaders = new ezcMailHeadersHolder();
                $this->parserState = $newPart ? self::PARSE_STATE_HEADERS : self::PARSE_STATE_POST_LAST;
            }
            else
            {
                // complete the work on the current part if there was any
                if ( $this->currentPartParser !== null )
                {
                    $part = $this->currentPartParser->finish();
                    if ( $part !== null ) // parsing failed
                    {
                        $this->partDone( $part );
                    }
                }

                // prepare for a new part if any
                $this->currentPartParser = null;
                $this->parserState =self::PARSE_STATE_POST_LAST;
                if ( $newPart )
                {
                    $this->parserState = self::PARSE_STATE_HEADERS;
                    $this->currentPartHeaders = new ezcMailHeadersHolder();
                }
            }
        }
        // normal data, pass to headers or current body
        else
        {
            if ( $this->parserState == self::PARSE_STATE_HEADERS && $line == '' )
            {
                $this->currentPartParser = self::createPartParserForHeaders( $this->currentPartHeaders );
                $this->parserState = self::PARSE_STATE_BODY;
            }
            else if ( $this->parserState == self::PARSE_STATE_HEADERS )
            {
                $this->parseHeader( $line, $this->currentPartHeaders );
            }
            else if ( $this->parserState == self::PARSE_STATE_BODY )
            {
                if ( $this->currentPartParser ) // we may have none if the part type was unknown
                {
                    // send body data to the part
                    $this->currentPartParser->parseBody( $origLine );
                }
            }
            // we are done parsing the multipart, ignore anything else pushed to us.
        }
    }
858103
def parse_header
      s0 = @current_pos
      s2 = match_regexp(/^[^*：\r\n]/)
      if s2 != :failed
        s1 = []
        while s2 != :failed
          s1 << s2
          s2 = match_regexp(/^[^：\r\n]/)
        end
      else
        s1 = :failed
      end
      if s1 != :failed
        if match_str("：") != :failed
          s3 = parse_nonls
          s5 = parse_nl
          if s5 != :failed
            s4 = []
            while s5 != :failed
              s4 << s5
              s5 = parse_nl
            end
          else
            s4 = :failed
          end
          if s4 != :failed
            @reported_pos = s0
            s0 = { "k" => s1.join, "v" => s3.join }
          else
            @current_pos = s0
            s0 = :failed
          end
        else
          @current_pos = s0
          s0 = :failed
        end
      else
        @current_pos = s0
        s0 = :failed
      end
      s0 = parse_header_teban if s0 == :failed
      s0
    end
309828
def parse_http_header(header_line):
    

    header_line = header_line.decode().strip()
    col_idx = header_line.find(':')

    if col_idx < 1:
        raise BadHttpHeaderError('Bad header: {}'.format(repr(header_line)))

    key = header_line[0:col_idx].strip()
    value = header_line[(col_idx+1):].strip()
    return HttpHeader(key=key, value=value)
777616
private void parse(String header)
   {
      ArrayList<String> list = new ArrayList<String>(4);
      StringBuilder sb = new StringBuilder();
      int index = 1;
      while (index < header.length())
      {
         char c = header.charAt(index++);
         if (Character.isDigit(c))
         {
            sb.append(c);
         }
         else
         {
            if (sb.length() != 0)
            {
               list.add(sb.toString());
               sb.setLength(0);
            }
         }
      }

      if (sb.length() != 0)
      {
         list.add(sb.toString());
      }

      m_id = list.get(0);
      m_sequence = Integer.parseInt(list.get(1));
      m_type = Integer.valueOf(list.get(2));
      if (list.size() > 3)
      {
         m_subtype = Integer.parseInt(list.get(3));
      }
   }
942293
def forbid_multi_line_headers(name, val):
    """"""
    val = smart_text(val)
    if "\n" in val or "\r" in val:
        raise BadHeaderError(
            "Header values can't contain newlines "
            "(got %r for header %r)" % (val, name)
        )
    try:
        val = val.encode("ascii")
    except UnicodeEncodeError:
        if name.lower() in ("to", "from", "cc"):
            result = []
            for item in val.split(", "):
                nm, addr = parseaddr(item)
                nm = str(Header(nm, DEFAULT_CHARSET))
                result.append(formataddr((nm, str(addr))))
            val = ", ".join(result)
        else:
            val = Header(val, DEFAULT_CHARSET)
    else:
        if name.lower() == "subject":
            val = Header(val)
    return name, val
160835
function parseHeaders(headers) {
    var out = {};
    var position = 0;
    while (position < headers.length) {
        var nameLength = headers.readUInt8(position++);
        var name = headers.slice(position, position + nameLength).toString();
        position += nameLength;
        switch (headers.readUInt8(position++)) {
            case 0 /* boolTrue */:
                out[name] = {
                    type: BOOLEAN_TAG,
                    value: true
                };
                break;
            case 1 /* boolFalse */:
                out[name] = {
                    type: BOOLEAN_TAG,
                    value: false
                };
                break;
            case 2 /* byte */:
                out[name] = {
                    type: BYTE_TAG,
                    value: headers.readInt8(position++)
                };
                break;
            case 3 /* short */:
                out[name] = {
                    type: SHORT_TAG,
                    value: headers.readInt16BE(position)
                };
                position += 2;
                break;
            case 4 /* integer */:
                out[name] = {
                    type: INT_TAG,
                    value: headers.readInt32BE(position)
                };
                position += 4;
                break;
            case 5 /* long */:
                out[name] = {
                    type: LONG_TAG,
                    value: new Int64(headers.slice(position, position + 8))
                };
                position += 8;
                break;
            case 6 /* byteArray */:
                var binaryLength = headers.readUInt16BE(position);
                position += 2;
                out[name] = {
                    type: BINARY_TAG,
                    value: headers.slice(position, position + binaryLength)
                };
                position += binaryLength;
                break;
            case 7 /* string */:
                var stringLength = headers.readUInt16BE(position);
                position += 2;
                out[name] = {
                    type: STRING_TAG,
                    value: headers.slice(
                        position,
                        position + stringLength
                    ).toString()
                };
                position += stringLength;
                break;
            case 8 /* timestamp */:
                out[name] = {
                    type: TIMESTAMP_TAG,
                    value: new Date(
                        new Int64(headers.slice(position, position + 8))
                            .valueOf()
                    )
                };
                position += 8;
                break;
            case 9 /* uuid */:
                var uuidChars = headers.slice(position, position + 16)
                    .toString('hex');
                position += 16;
                out[name] = {
                    type: UUID_TAG,
                    value: uuidChars.substr(0, 8) + '-' +
                        uuidChars.substr(8, 4) + '-' +
                        uuidChars.substr(12, 4) + '-' +
                        uuidChars.substr(16, 4) + '-' +
                        uuidChars.substr(20)
                };
                break;
            default:
                throw new Error('Unrecognized header type tag');
        }
    }
    return out;
}
1373923
def parse_results_header(cls, header):
        
        header = IORMetricsExtractor.RE_MULTIPLE_SPACES.sub(' ', header)
        header = header.split(' ')
        return header
974797
void parseNextResponse() throws IOException {
    contentId++;

    // Extract the outer headers.
    String line;
    while ((line = readLine()) != null && !line.equals("")) {
      // Do nothing.
    }

    // Extract the status code.
    String statusLine = readLine();
    String[] statusParts = statusLine.split(" ");
    int statusCode = Integer.parseInt(statusParts[1]);

    // Extract and store the inner headers.
    // TODO(rmistry): Handle inner headers that span multiple lines. More details here:
    // http://tools.ietf.org/html/rfc2616#section-2.2
    List<String> headerNames = new ArrayList<String>();
    List<String> headerValues = new ArrayList<String>();
    long contentLength = -1L;
    while ((line = readLine()) != null && !line.equals("")) {
      String[] headerParts = line.split(": ", 2);
      String headerName = headerParts[0];
      String headerValue = headerParts[1];
      headerNames.add(headerName);
      headerValues.add(headerValue);
      if ("Content-Length".equalsIgnoreCase(headerName.trim())) {
          contentLength = Long.parseLong(headerValue);
      }
    }

    InputStream body;
    if (contentLength == -1) {
      // This isn't very efficient, but most respectable servers should set the Content-Length
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while ((line = readRawLine()) != null && !line.startsWith(boundary)) {
        // Convert characters back to bytes:
        buffer.write(line.getBytes("ISO-8859-1"));
      }

      // Remove CRLF that separates body from boundary token
      body = trimCrlf(buffer.toByteArray());

      // Remove CRLF from the boundary token (to match readLine)
      line = trimCrlf(line);
    } else {
      body = new FilterInputStream(ByteStreams.limit(inputStream, contentLength)) {
        @Override
        public void close() {
          // Don't allow the parser to close the underlying stream
        }
      };
    }

    HttpResponse response =
        getFakeResponse(statusCode, body, headerNames, headerValues);

    parseAndCallback(requestInfos.get(contentId - 1), statusCode, response);

    // Consume any bytes that were not consumed by the parser
    while (body.skip(contentLength) > 0 || body.read() != -1) {
    }

    if (contentLength != -1) {
      line = readLine();
    } else {
      // The line was already read
    }
    // Consume any blank lines that follow the response (not included in Content-Length)
    while ((line != null) && (line.length() == 0)) {
      line = readLine();
    }

    checkForFinalBoundary(line);
  }
146710
public function parseBody( $line )
    {
        $this->parseHeader( $line, $this->headers );
        $this->size += strlen( $line );
    }