Deno簡易テストサーバ

2406 ワード

リクエスト情報の表示をテストするために、簡単なサーバを一時的に起動する必要がある場合があります.ちょうどDeno公式サイトの例で変更しました.Node.jsで書くのも便利です.
スタートアップコマンド
deno run --allow-net server.ts
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
import { serve } from "https://deno.land/[email protected]/http/server.ts";

interface Args {
  _: string[];
  // --prot
  port?: number;
  // --on-headers
  "on-headers"?: boolean;
}

const args = parse(Deno.args); //  

/**
 *   deno run --allow-net server.ts
 */
const PORT = args.port ? args.port : 7070;
const server = serve({ port: PORT });
console.log(
  `HTTP webserver running.  Access it at:  http://localhost:${PORT}/`
);

for await (const request of server) {
  if (request.url !== "/favicon.ico") {
    const time = formatTimestamp(new Date().getTime());
    console.log("");
    console.log(
      `\x1b[32m[${time}]\x1b[0m method: ${request.method} url: ${request.url}`
    );
    if (args["on-headers"]) console.log(`headers: `, request.headers);
  }
  request.respond({ status: 200, body: "ok" });
}

/**
 *  
 * @param timestamp
 * @param options
 * @returns
 */
function formatTimestamp(
  timestamp: number,
  options?: {
    dateSection: boolean;
    timeSection: boolean;
    dateSign: string;
    timeSign: string;
    linkSign: string;
    places: number;
  }
) {
  const $d = new Date(
    timestamp.toString().length === 10 ? timestamp * 1000 : timestamp
  );
  if ($d.toString() === "Invalid Date") return "Invalid Date";
  const {
    dateSection = true,
    timeSection = true,
    dateSign = "-",
    timeSign = ":",
    linkSign = " ",
    places = 2,
  } = options || {};

  const padStart = (string: number, length = places) => {
    const s = String(string);
    if (!s || s.length >= length) return string;
    return `${Array(length + 1 - s.length).join("0")}${string}`;
  };

  const $y = $d.getFullYear(),
    $M = padStart($d.getMonth() + 1),
    $D = padStart($d.getDate()),
    $H = padStart($d.getHours()),
    $m = padStart($d.getMinutes()),
    $s = padStart($d.getSeconds());

  let text = "";
  if (dateSection) text += `${$y}${dateSign}${$M}${dateSign}${$D}`;
  if (timeSection) text += `${linkSign}${$H}${timeSign}${$m}${timeSign}${$s}`;

  return text;
}