{"size": 926, "ext": "js", "max_stars_repo_path": "server/http/response.js", "max_stars_repo_name": "szdailei/core", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/http/response.js", "max_issues_repo_name": "szdailei/core", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/http/response.js", "max_forks_repo_name": "szdailei/core", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.5348837209, "max_line_length": 62, "alphanum_fraction": 0.6933045356}
import http from 'http';
import { PassThrough } from 'stream';

function sendResponseBySteam(res, statusCode, statusMessage) {
  res.writeHead(statusCode);

  const bufferStream = new PassThrough();
  bufferStream.end(Buffer.from(statusMessage));
  bufferStream.pipe(res);
}

/**
@require res.headersSent is false
*/
function sendResponse(res, statusCode, statusMessage) {
  if (statusMessage) {
    sendResponseBySteam(res, statusCode, statusMessage);
  } else {
    res.writeHead(statusCode);
    res.end();
  }
}

function notFound(res) {
  if (res.headersSent) {
    res.end();
    return;
  }
  res.setHeader('Content-Type', 'text/plain');
  sendResponse(res, 404, http.STATUS_CODES[404]);
}

function forbidden(res) {
  if (res.headersSent) {
    res.end();
    return;
  }
  res.setHeader('Content-Type', 'text/plain');
  sendResponse(res, 403, http.STATUS_CODES[403]);
}

export { sendResponse, notFound, forbidden };
