var http = require('http');
var url = require('url');
var config = require('../lib/config');
var util = require('../lib/util');

function parseHeaders(headers, rawHeaderNames) {
  if (!headers || typeof headers != 'string') {
    return {};
  }

  try {
    return util.lowerCaseify(JSON.parse(headers), rawHeaderNames);
  } catch(e) {}

  return util.parseHeaders(headers, rawHeaderNames);
}

function getMethod(method) {
  if (typeof method !== 'string') {
    return 'GET';
  }
  return method.toUpperCase();
}

function isWebSocket(options) {
  var protocol = options.protocol;
  if (protocol === 'ws:' || protocol === 'wss:') {
    return true;
  }
  // TODO: 判断headers
}

function isConnect(options) {
  if (options.method === 'CONNECT') {
    return true;
  }
  var p = options.protocol;
  return p === 'connect:' || p === 'socket:' || p === 'tunnel:';
}

function handleConnect(options) {

}

function handleWebSocket(options) {

}

function handleHttp(options) {
  if (options.protocol === 'https:') {
    options.headers[config.HTTPS_FIELD] = 1;
  }
  options.protocol = null;
  options.hostname = null;
  options.host = '127.0.0.1';
  options.port = config.port;
  http.request(options, function(res) {
    res.on('error', util.noop);
    util.drain(res);
  }).on('error', util.noop).end(options.body);
}

module.exports = function(req, res) {
  var fullUrl = req.body.url;
  if (!fullUrl || typeof fullUrl !== 'string') {
    return res.json({ec: 0});
  }

  fullUrl = util.encodeNonAsciiChar(fullUrl.replace(/#.*$/, ''));
  var options = url.parse(util.setProtocol(fullUrl));
  if (!options.host) {
    return res.json({ec: 0});
  }

  var rawHeaderNames = {};
  var headers = parseHeaders(req.body.headers, rawHeaderNames);
  if (!headers['user-agent']) {
    headers['user-agent'] = 'whistle/' + config.version;
  }
  headers.host = options.host;
  headers[config.CLIENT_IP_HEAD] = util.getClientIp(req);
  options.method = getMethod(req.body.method);

  if (headers['content-length'] != null) {
    req.body.body = util.toBuffer(req.body.body || '');
    headers['content-length'] = req.body.body.length;
  }
  options.headers = util.formatHeaders(headers, rawHeaderNames);
  options.body = req.body.body;
  if (isConnect(options)) {
    handleConnect(options);
  } else if (isWebSocket(options)) {
    handleWebSocket(options);
  } else {
    handleHttp(options);
  }

  res.json({ec: 0, em: 'success'});
};

@@ -869,33 +869,367 @@
 ion 
-handleConnect(options) %7B%0A
+drain(socket) %7B%0A  socket.on('error', util.noop);%0A  socket.on('data', util.noop);%0A%7D%0A%0Afunction handleConnect(options) %7B%0A  options.headers%5B'x-whistle-policy'%5D = 'tunnel';%0A  config.connect(%7B%0A    host: options.hostname,%0A    port: options.port,%0A    proxyHost: '127.0.0.1',%0A    proxyPort: config.port,%0A    headers: options.headers%0A  %7D, drain).on('error', util.noop);
 %0A%7D%0A%0A

Support build connect