add some utility methods to http response.

@param {*} [res]
964742
function extendHttpResponse(res) {
    res = res || express.response;

    function callbackFnFn(verbFunc) {
        return function (next, status) {
            var res = this;
            return function (err, result) {
                if (err) {
                    return next(err);
                }
                if (status) {
                    return res.status(status);
                }
                return verbFunc.call(res, result);
            };
        };
    }

    function laterFnFn(verbFunc) {
        return function (promise, next, status) {
            var res = this;
            return Q.when(promise).then(function (result) {
                if (status) {
                    res.status(status);
                }
                return verbFunc.call(res, result);
            }).fail(next).done();
        };
    }

    //
    // callback helpers
    //

    /**
     * create generic node.js callback function to invoke 'express.response.send()'.
     *
     * ex.
     * ```
     * var fs = require('fs');
     * app.get('/foo', function(req, res, next) {
     *   fs.readFile('foo.txt', res.sendCallbackFn(next));
     * });
     * ```
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send response.
     * @method
     * @memberOf {express.request}
     */
    res.sendCallbackFn = callbackFnFn(res.send);

    /**
     * create generic node.js callback function to invoke 'express.response.json()'.
     *
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send 'json' response.
     * @method
     * @memberOf {express.request}
     */
    res.jsonCallbackFn = callbackFnFn(res.json);

    /**
     * create generic node.js callback function to invoke 'express.response.jsonp()'.
     *
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send 'jsonp' response.
     * @method
     * @memberOf {express.request}
     */
    res.jsonpCallbackFn = callbackFnFn(res.jsonp);

    /**
     * create generic node.js callback function to invoke 'express.response.sendFile()'.
     *
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send 'sendFile' response.
     * @method
     * @memberOf {express.request}
     */
    res.sendFileCallbackFn = callbackFnFn(res.sendFile);

    /**
     * create generic node.js callback function to invoke 'express.response.redirect()'.
     *
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send 'redirect' response.
     * @method
     * @memberOf {express.request}
     */
    res.redirectCallbackFn = callbackFnFn(res.redirect);

    /**
     * ex.
     * ```
     * fs.stat('foo.txt', res.renderCallbackFn('stat_view', next));
     * ```
     *
     * @param {string} view
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)}
     * @memberOf {express.response}
     */
    res.renderCallbackFn = function (view, next, status) {
        var res = this;
        return function (err, result) {
            if (err) {
                return next(err);
            }
            if (status) {
                res.status(status);
            }
            return res.render(view, result);
        };
    };

    //
    // promise helpers
    //

    /**
     * promise version to invoke `express.response.send()`.
     *
     * ex.
     * ```
     * var FS = require('q-io/fs');
     * app.get('/foo', function (req, res, next) {
     *   res.sendLater(FS.readFile('foo.txt'), next);
     * })
     * ```
     *
     * @param {promise|*} promise of response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.sendLater = laterFnFn(res.send);

    /**
     * promise version of `express.response.json()`.
     *
     * @param {promise|*} promise of 'json' response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.jsonLater = laterFnFn(res.json);

    /**
     * promise version of `express.response.jsonp()`.
     *
     * @param {promise|*} promise of 'jsonp' response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.jsonpLater = laterFnFn(res.jsonp);

    /**
     * promise version of `express.response.sendFile()`.
     *
     * @param {promise|*} promise of 'sendFile' response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.sendFileLater = laterFnFn(res.sendFile);

    /**
     * promise version of `express.response.redirect()`.
     *
     * @param {promise|*} promise of 'redirect' response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.redirectLater = laterFnFn(res.redirect);

    /**
     *
     * ex.
     * ```
     * var FS = require('q-io/fs');
     * res.renderLater('stat_view', FS.stat('foo.txt'), next);
     * ```
     *
     * @param {string} view
     * @param {promise|*} promise of 'render' model.
     * @param {function} next
     * @param {number} [status]
     * @memberOf {express.response}
     */
    res.renderLater = function (view, promise, next, status) {
        var res = this;
        return Q.when(promise).then(function (result) {
            if (status) {
                res.status(status);
            }
            return res.render(view, result);
        }).fail(next).done();
    };
}
757142
def resend(self):
        """"""
        response = self.api_client._post(self.resource_path, 'resend')
        return self.api_client._make_api_object(response, APIObject)
1164828
function sendHTMLErrorCode(code, message, res) {
  return function () {
    res.type('html');
    res.send(code + ' ' + message);
  };
}
7603
def on_headers(self, response, exc=None):
        ''''''

        if response.status_code == 101:
            connection = response.connection
            request = response.request
            handler = request.websocket_handler
            if not handler:
                handler = WS()
            parser = request.client.frame_parser(kind=1)
            consumer = partial(WebSocketClient.create,
                               response, handler, parser)
            connection.upgrade(consumer)
            response.event('post_request').fire()
            websocket = connection.current_consumer()
            response.request_again = lambda r: websocket
576483
function requestHandler (method) {
  return function (req, res, next) {
    method.call(this, req, responseHandler(res, next));
  }.bind(this);
}
1328497
async def _wrap_http(self, handler, *args, **kwargs):
        ''' '''
        try:
            method = self.request_method()
            # support preflight requests when CORS is enabled
            if method == 'OPTIONS':
                return self.build_http_response(None, status=NO_CONTENT)
            data = await handler(self, *args, **kwargs)
            # format the response object
            formatted = self.format(method, data)
            status = self.responses.get(method, OK)
            return self.build_http_response(formatted, status=status)
        except Exception as ex:
            return self.dispatch_error(ex)
530574
function respOk (response, data, type) {
    if (type) {
        headers = {'Content-Type': type};
    }
    response.writeHead(200, headers);
    if (data) {
        response.write(data, 'utf-8');
    }
    response.end();
}
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);
        });
      }
171237
function on_connect(res){
	//console.log('STATUS: ' + res.statusCode);
	//console.log('HEADERS: ' + JSON.stringify(res.headers));
	res.setEncoding('utf8');
	var raw_data = '';
	res.on('data', function (chunk) {
	    //console.log('BODY: ' + chunk);
	    raw_data = raw_data + chunk;
	});
	// Throw to .
	res.on('end', function () {
	    //console.log('END with: ' + raw_data);
	    var response = new anchor._response_handler(raw_data);
	    if( response && response.okay() ){
		anchor.apply_callbacks('success', [response, anchor]);
	    }else{
		// Make sure that there is something there to
		// hold on to.
		if( ! response ){
		    response = new anchor._response_handler(null);
		    response.okay(false);
		    response.message_type('error');
		    response.message('null response');
		}else{
		    response.message_type('error');
		    response.message('bad response');
		}
		anchor.apply_callbacks('error', [response, anchor]);
	    }
	});
    }
82856
function (res, args) {
            // callback args preparation
            var requestObject = args.requestObject, actionQueuing = args.actionQueuing;
            var id = args.id, senderObject = args.senderObject;
            // var cb = args.cb, session = args.session, requestHandler = args.requestHandler

            // starts right now for next item in action queuing
            if (actionQueuing) {
                actionQueuing.handleNextRequest(id);
            }

            // updated resources
            var newRes = {
                requestUrl : res.url,
                requestObject : requestObject,
                responseXML : res.responseXML,
                responseText : res.responseText,
                responseJSON : res.responseJSON,
                status : res.status, // http status (e.g.: 404)
                error : res.error, // contains error message

                // Should we stop supporting the following properties ?
                // These properties can be set by IO filters (through the sender object) to bypass the response handler
                data : senderObject.responseData,
                errorData : senderObject.responseErrorData
            };

            args.res = newRes;

            this._processOnResponse(args);
        }
447972
function (req, res) {
        return function (err) {
            if (err) {
                res.writeHead(500);
                res.end(err.toString());
            } else {
                res.writeHead(404);
                res.end();
            }
        };
    }
310508
function clientRes(res) {
    if (!res || !res.statusCode) {
        return (res);
    }

    return ({
        statusCode: res.statusCode,
        headers: res.headers
    });
}
734429
function responseHandler (res, next) {
  return function (err, message) {
    if (err || !message) {
      next(err);
    } else {
      res.send(message);
    }
  }
}
1245170
function parseHttpResponse(options, filesWithHash) {
    if (options.verbose) {
        _utils.logger.info('Parsing HTTP responses...');
    }
    var promises = [];
    var _iteratorNormalCompletion5 = true;
    var _didIteratorError5 = false;
    var _iteratorError5 = undefined;

    try {
        for (var _iterator5 = filesWithHash[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
            var fileWithHash = _step5.value;

            if (fileWithHash.subtitlesPresent) continue;
            var p = (0, _utils.XML2JSON)(options, fileWithHash).catch(function (err) {
                if (options.verbose) {
                    _utils.logger.info('Error in HTTP response: ', err.err);
                }
                return err.fileWithHash;
            });
            promises.push(p);
        }
    } catch (err) {
        _didIteratorError5 = true;
        _iteratorError5 = err;
    } finally {
        try {
            if (!_iteratorNormalCompletion5 && _iterator5.return) {
                _iterator5.return();
            }
        } finally {
            if (_didIteratorError5) {
                throw _iteratorError5;
            }
        }
    }

    return Promise.all(promises);
}
168642
function (res_obj, data, conn) {

		// check if we should return empty response
		if (typeof res_obj === 'undefined') {
			SR.REST.reply(res, {});
			return true;
		}

		// check for special case processing (SR_REDIRECT)
		if (res_obj[SR.Tags.UPDATE] === 'SR_REDIRECT' && res_obj[SR.Tags.PARA] && res_obj[SR.Tags.PARA].url) {

			var url = res_obj[SR.Tags.PARA].url;
			LOG.warn('redirecting to: ' + url, l_name);

			/*
			res.writeHead(302, {
				'Location': url
			});
			res.end();
			*/

			// redirect by page 
			// TODO: merge with same code in FB.js
			var page =
				'<html><body><script>\n' +
				'if (navigator.appName.indexOf("Microsoft") != -1)\n' +
				'    window.top.location.href="' + url + '";\n' +
				'else\n' +
				'	 top.location.href="' + url + '";\n' +
				'</script></body></html>\n';

			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			res.end(page);

			return true;
		}
		
		// check for special case processing (SR_HTML)
		if (res_obj[SR.Tags.UPDATE] === 'SR_HTML' && res_obj[SR.Tags.PARA].page) {
			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			res.end(res_obj[SR.Tags.PARA].page);
			return true;
		}

		// check for special case processing (SR_DOWNLOAD)
		if (res_obj[SR.Tags.UPDATE] === 'SR_DOWNLOAD' && res_obj[SR.Tags.PARA].data && res_obj[SR.Tags.PARA].filename) {

			var filename = res_obj[SR.Tags.PARA].filename;
			LOG.warn('allow client to download file: ' + filename, l_name);

			var data = res_obj[SR.Tags.PARA].data;
			res.writeHead(200, {
				'Content-Type': 'application/octet-stream',
				'Content-Disposition': 'attachment; filename=' + filename,
				'Content-Length': data.length
			});
			res.end(data);
			return true;
		}

		// check for special case processing (SR_RESOURCE)
		if (res_obj[SR.Tags.UPDATE] === 'SR_RESOURCE' && res_obj[SR.Tags.PARA].address) {

			var file = res_obj[SR.Tags.PARA].address;
						
			// check if resource exists & its states
			SR.fs.stat(file, function (err, stats) {
										
				var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
				
				if (err) {			
					LOG.error(err, l_name);
					res.writeHead(404, resHeader);
					res.end();
					return;
				}
				
				var extFilename = file.match(/[\W\w]*\.([\W\w]*)/)[1];
				if (typeof extFilename === 'string')
					extFilename = extFilename.toLowerCase();
				
				// default to 200 status
				var resStatus = 200;
				resHeader['Accept-Ranges'] = 'bytes';
				resHeader['Cache-Control'] = 'no-cache';
				resHeader['Content-Length'] = stats.size;
				
				if (l_extList[extFilename]) {
					resHeader['Content-Type'] = l_extList[extFilename];
				};
				
				var start = undefined;
				var end = undefined;
				
				// check if request range exists (e.g., streaming media such as webm/mp4) to return 206 status
				// see: https://delog.wordpress.com/2011/04/25/stream-webm-file-to-chrome-using-node-js/						
				if (req.headers.range) {
					var range = req.headers.range.split(/bytes=([0-9]*)-([0-9]*)/);
					resStatus = 206;
					
					start = parseInt(range[1] || 0);
					end = parseInt(range[2] || stats.size - 1);
					
					if (start > end) {
						LOG.error('stream file start > end. start: ' + start + ' end: ' + end, l_name);
						var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
						res.writeHead(404, resHeader);
						res.end();
						return;  // abnormal if we've reached here
					}
					
					LOG.debug('requesting bytes ' + start + ' to ' + end + ' for file: ' + file, l_name);
							 
					resHeader['Connection'] = 'close';
					resHeader['Content-Length'] = end - start + 1;
					resHeader['Content-Range'] = 'bytes ' + start + '-' + end + '/' + stats.size;
					resHeader['Transfer-Encoding'] = 'chunked';
				} 
				// otherwise assume it's a regular file
				else if (l_directExt.hasOwnProperty(extFilename)) {
					// NOTE: code below will cause the file be downloaded in a "Save As.." format
					// (instead of being displayed directly), we only want this behavior for certain file types (such as .zip)				
					var filename = file.replace(/^.*[\\\/]/, '')
					LOG.warn('requesting a file: ' + filename, l_name);
					resHeader['Content-Disposition'] = 'attachment; filename=' + filename;
				}
				
				LOG.sys('SR_RESOURCE header:', l_name);
				LOG.sys(resHeader);
				res.writeHead(resStatus, resHeader);

				// start streaming
				SR.fs.createReadStream(file, {
					flags: 'r',
					start: start,
					end: end
				}).pipe(res);			
			});
			
			return true;
		}

		var origin = _getOrigin(req);

		// send back via res object if hadn't responded yet
		if (res.headersSent === false) {
			// NOTE: cookie may be undefined;
			SR.REST.reply(res, data, {
				origin: origin,
				cookie: cookie
			});
		}
		else {
			LOG.error('HTTP request has already responded (cannot respond twice)', l_name);
			LOG.stack();
		}

		return true;
	}
89497
function process_axios_response(axios_response) {
                const response = {
                    status: {
                        code: axios_response.status,
                        text: axios_response.statusText,
                        }, // eslint-disable-line indent
                    headers: axios_response.headers,
                    data: axios_response.data,
                    }; // eslint-disable-line indent
                if (params.preparer) {
                    const request_metadata = Object.assign({}, params);
                    delete request_metadata.preparer;
                    response.data = params.preparer(request_metadata, response);
                }
                return resolve_promise(response);
            }
245886
def convert_response(response)
      HttpResponse.new(response.status, response.headers, response.body)
    end