Create a function to handle the final response.

@param {Request} req
@param {Response} res
@param {Object} [options]
@return {Function}
@public
761239
function finalhandler (req, res, options) {
  var opts = options || {}

  // get environment
  var env = opts.env || process.env.NODE_ENV || 'development'

  // get error callback
  var onerror = opts.onerror

  return function (err) {
    var headers
    var msg
    var status

    // ignore 404 on in-flight response
    if (!err && headersSent(res)) {
      debug('cannot 404 after headers sent')
      return
    }

    // unhandled error
    if (err) {
      // respect status code from error
      status = getErrorStatusCode(err)

      if (status === undefined) {
        // fallback to status code on response
        status = getResponseStatusCode(res)
      } else {
        // respect headers from error
        headers = getErrorHeaders(err)
      }

      // get error message
      msg = getErrorMessage(err, status, env)
    } else {
      // not found
      status = 404
      msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req))
    }

    debug('default %s', status)

    // schedule onerror callback
    if (err && onerror) {
      defer(onerror, err, req, res)
    }

    // cannot actually respond
    if (headersSent(res)) {
      debug('cannot %d after headers sent', status)
      req.socket.destroy()
      return
    }

    // send response
    send(req, res, status, headers, msg)
  }
}
1108586
function createMiddleware(options) {
  /**
   * Express middleware handling raw content requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   */
  return async (req, res, next) => {
    const { owner } = req.params;
    const repoName = req.params.repo;
    let refName = req.params.ref;
    let fpath = req.params[0];

    const repPath = resolveRepositoryPath(options, owner, repoName);

    // issue: #53: handle branch names containing '/' (e.g. 'foo/bar')
    const parsed = await determineRefPathName(repPath, `${req.params.ref}/${req.params[0]}`);
    if (parsed) {
      refName = parsed.ref;
      fpath = parsed.pathName;
    }

    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    // project-helix/#187: serve modified content only if the requested ref is currently checked out
    isCheckedOut(repPath, refName)
      .then(serveUncommitted => resolveBlob(repPath, refName, fpath, serveUncommitted))
      .then((oid) => {
        const mimeType = mime.getType(fpath) || 'text/plain';
        res.writeHead(200, {
          'Content-Type': mimeType,
          ETag: oid,
          // TODO: review cache-control header
          'Cache-Control': 'max-age=0, private, must-revalidate',
        });
        createBlobReadStream(repPath, oid)
          .then(stream => stream.pipe(res));
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'TreeOrBlobNotFoundError' || err.code === 'ResolveRefError') {
          options.logger.debug(`[rawHandler] resource not found: ${err.message}`);
          res.status(404).send('not found.');
        } else {
          options.logger.debug(`[rawHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
967063
function create (options) {
  const {
    xForwardedProto,
    redirectPort,
    redirectHost,
    statusCode,
    redirectUnknown,
    redirect,
    exclude
  } = Object.assign({}, defaults, options)
  const _port = redirectPort === 443 ? '' : (': ' + redirectPort)

  return function redirectSSL (req, res, next) {
    if (redirect && !isExcluded(req.url, exclude)) {
      const _isHttps = isHTTPS(req, xForwardedProto)
      const shouldRedirect = _isHttps === false || (redirectUnknown && _isHttps === null)
      if (shouldRedirect) {
        const ـredirectURL = 'https://' + (redirectHost || req.headers.host) + _port + req.url
        res.writeHead(statusCode, { Location: ـredirectURL })
        return res.end()
      }
    }

    return next()
  }
}
734429
function responseHandler (res, next) {
  return function (err, message) {
    if (err || !message) {
      next(err);
    } else {
      res.send(message);
    }
  }
}
1232940
function rereq(options, done) {
  let req;

  req = https.request(options, (res) => {
    let chunk = '';

    res.on('data', (data) => {
      chunk += data;
    });
    res.on('end', () => {
      done(null, chunk.toString('utf8'));
    });
  });
  req.on('error', (e) => {
    done(e);
  });
  req.end();
}
550750
function(url, options, defaults) {
            var d = Q.defer();
            options = options || {};
            options = _.extend(options, defaults, {
                "url": url
            });
            var r = new Requests(options);
            r.on("done", function(content) {
                d.resolve(content);
            });
            r.on("error", function(err) {
                var e = new Error(err.textStatus+": "+err.content);
                e.textStatus = err.textStatus,
                e.httpRes = err.content;
                d.reject(e);
            });

            r.execute();
            return d.promise;
        }
25833
function(options) {
        var params = this.toJSON();
        params.limit = 0;
        params.count = 1;
        var request = this._createRequest(params, options);

        return request.then(function(response) {
          return response.count;
        });
      }
67307
function Request(options) {
  return new Promise(function(resolve, reject) {
    client(options, function(err, res) {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  });
}
1039652
def handle_response(defopts, res)
      raise NetError.new(res.body)  unless res.code == '200'

      json = Yajl::Parser.parse(res.body)
      RegApi2.got_response(json)

      raise ApiError.from_json(json)  if json['result'] == 'error'

      res_contract = RegApi2::ResultContract.new(defopts)
      res_contract.handle_result(json)
    end
489827
function request(url, options, callback)
{
  var connection;

  if (typeof options == 'function')
  {
    callback = options;
    options  = {};
  }

  connection = hyperquest(url, options, once(function(error, response)
  {
    if (error)
    {
      callback(error, response);
      return;
    }

    // set body
    response.body = '';

    // accumulate response body
    response.on('data', function(data)
    {
      response.body += data.toString();
    });

    response.on('end', function()
    {
      callback(null, response);
    });
  }));

  return connection;
}
1347703
function(operation, res) {
      var that = this;
      var method = res.req.method;

      return operation.then(function(doc) {
        if (method === 'POST') {
          if (that._path && (that._key || that._index)) {
            res.header('Location', '/' + that._path + '/' + doc[that._key || that._index]);
          }

          return res.status(201).json(doc);
        }

        return res.status(200).json(doc);
      }, function(err) {
        console.error(err.message);

        if (method === 'POST' || method === 'PUT') {
          return res.status(409).end();
        }

        if (method === 'GET') {
          res.status(404).end();
        }

        return res.status(500).end();
      });
    }
773066
function reply(req, res, opts) {
  opts = opts || {};

  return function(statusCode, body) {
    var call = { args: [].slice.call(arguments) };

    // handle single argument replies
    if (typeof statusCode === 'string') {
      body = { message: statusCode };
      statusCode = 200;
    } else if (statusCode instanceof Error) {
      body = statusCode;
      statusCode = 500;
    }

    // handle error objects in replies
    if (body instanceof Error) {
      if (typeof body.statusCode === 'number') {
        statusCode = body.statusCode;
      }
      if (body.expose) {
        body = body.toJSON ? body.toJSON() : { message: body.message };
      } else {
        body = undefined;
      }
    }

    // default message
    if (body === undefined) {
      body = { message: http.STATUS_CODES[statusCode] || 'unknown response' };
    }

    call.statusCode = statusCode;
    call.body = body;

    // allow user to override body before sending
    if (req.sf.responseMessage) {
      call = req.sf.responseMessage(call);

      if (!call) {
        debug('responseMessage handled reply');
        return;
      }

      statusCode = call.statusCode;
      body = call.body;
    }

    var length = 0;
    var type;

    if (body !== undefined) {
      if (Buffer.isBuffer(body)) {
        length = body.length;
      } else if (res.sf && res.sf.produce) {
        type = res.sf.produce.mime;
        body = res.sf.produce.encoder(body);
        length = Buffer.byteLength(body, CHARSET);
      } else {
        type = 'application/json';
        body = encoder[type](body);
        length = Buffer.byteLength(body, CHARSET);
      }
    }

    var noContent = statusCode === 204 || statusCode === 304;

    if (!noContent && !res.headersSent) {
      if (type && !res.getHeader('content-type') ||
        res.getHeader('content-type') !== type) {
        res.setHeader('content-type', type + '; charset=' + CHARSET);
      }

      if (!res.getHeader('content-length') ||
        res.getHeader('content-length') !== length) {
        res.setHeader('content-length', length);
      }

      // add etag header if not already set
      if (opts.etag && body && body.length && !res.getHeader('etag') &&
          req.method === 'GET' && Math.floor(statusCode / 100) === 2) {
        var etag = crypto.createHash('md5').update(body).digest('hex');
        res.setHeader('etag', etag);
      }

      // if cache is fresh set status code to 304
      if (fresh(req.headers, res._headers)) {
        statusCode = 304;
        noContent = true;
      }

      if (noContent) {
        res.removeHeader('content-type');
        res.removeHeader('content-length');
        res.removeHeader('transfer-encoding');
      }
    }

    if (noContent) body = '';

    res.statusCode = statusCode;

    return res.end(req.method === 'HEAD' ? null : body);
  };
}
1041759
function requestHandler(req, res, next) {
  const params = req && req.params;
  const start = Date.now();
  let source;
  let opts;

  return Promise.try(() => {
    source = core.getPublicSource(params.src);

    if (!_.contains(source.formats, params.format)) {
      throw new Err('Format %s is not known', params.format).metrics('err.req.format');
    }

    params.z = core.validateZoom(params.z, source);
    params.scale = core.validateScale(params.scale, source);

    params.x = checkType.strToInt(params.x);
    params.y = checkType.strToInt(params.y);
    if (
      !qidx.isValidCoordinate(params.x, params.z) || !qidx.isValidCoordinate(params.y, params.z)
    ) {
      throw new Err('x,y coordinates are not valid, or not allowed for this zoom').metrics('err.req.coords');
    }

    opts = {
      z: params.z,
      x: params.x,
      y: params.y,
    };
    if (params.format !== 'pbf') {
      // Ensure that PNGs are not 32bit
      // TODO: this should be source-configurable
      opts.format = params.format === 'png' ? 'png8:m=h' : params.format;
      if (params.scale) {
        opts.scale = params.scale;
      }
    }
    if (req.query && req.query.lang) {
      if (!langCodeRe.test(req.query.lang)) {
        throw new Err('lang param is not valid').metrics('err.req.lang');
      }
      opts.lang = req.query.lang;
    }

    // fixme: Force all tiles to be treated as vector
    opts.treatAsVector = true;

    return source.getHandler().getAsync(opts);
  }).then((result) => {
    let mx;

    core.setResponseHeaders(res, source, result.headers);

    if (params.format === 'json') {
      // Allow JSON to be shortened to simplify debugging
      res.json(filterJson(req.query, result.data));
    } else {
      res.send(result.data);
    }

    mx = util.format('req.%s.%s.%s', params.src, params.z, params.format);
    if (params.scale) {
      // replace '.' with ',' -- otherwise grafana treats it as a divider
      mx += `.${params.scale.toString().replace('.', ',')}`;
    }
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
1115793
function (res, res_obj) {

    // return response if exist, otherwise response might be returned 
    // AFTER some callback is done handling (i.e., response will be returned within the handler)
    if (typeof res_obj === 'string') {
        LOG.sys('replying a string: ' + res_obj);
        res.writeHead(200, {'Content-Type': 'text/plain'});                     
        res.end(res_obj);            
    }
    else {
        LOG.sys('replying a JSON: ' + JSON.stringify(res_obj));
        res.writeHead(200, {'Content-Type': 'application/json'});                     
        res.end(JSON.stringify(res_obj));        
    }
}
525895
function(options) {
    return function(err, resp) {
      if (err) {
        options.error(err);
      } else {
        options.success(resp);
      }
    };
  }
932334
function responseHandler(resp) {
        // Set response var to the response we got back
        // This is so it remains accessable outside this scope
        response = resp;
        // Check for redirect
        // @TODO Prevent looped redirects
        if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
          // Change URL to the redirect location
          settings.url = response.headers.location;
          var url = Url.parse(settings.url);
          // Set host var in case it's used later
          host = url.hostname;
          // Options for the new request
          var newOptions = {
            hostname: url.hostname,
            port: url.port,
            path: url.path,
            method: response.statusCode === 303 ? "GET" : settings.method,
            headers: headers,
            withCredentials: self.withCredentials
          };

          // Issue the new request
          request = doRequest(newOptions, responseHandler).on("error", errorHandler);
          request.end();
          // @TODO Check if an XHR event needs to be fired here
          return;
        }

        response.setEncoding("utf8");

        setState(self.HEADERS_RECEIVED);
        self.status = response.statusCode;

        response.on("data", function(chunk) {
          // Make sure there's some data
          if (chunk) {
            self.responseText += chunk;
          }
          // Don't emit state changes if the connection has been aborted.
          if (sendFlag) {
            setState(self.LOADING);
          }
        });

        response.on("end", function() {
          if (sendFlag) {
            // Discard the end event if the connection has been aborted
            setState(self.DONE);
            sendFlag = false;
          }
        });

        response.on("error", function(error) {
          self.handleError(error);
        });
      }
576483
function requestHandler (method) {
  return function (req, res, next) {
    method.call(this, req, responseHandler(res, next));
  }.bind(this);
}