0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

URLのHTTPパラメータに指定した文字列をプロンプトに含める

0
Posted at

HTTPパラメータから文字列を取得する

URLPatternは、Denoが標準で提供している、URLをパターンマッチングで解析するAPI。
http://localhost/:nameというURLをパターンとして指定すると:nameの部分に指定された文字列をnameという変数値として取得できる。

// main.ts

import OpenAI from "@openai/openai";

const endpoint = Deno.env.get("AZURE_OPENAI_ENDPOINT") ?? "";
const deployment_name = Deno.env.get("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4.1-mini";
const api_key = Deno.env.get("AZURE_OPENAI_API_KEY") ?? "";

const client = new OpenAI({
  baseURL: endpoint,
  apiKey: api_key,
});

// `http://localhost:8000/おでん` -> name=`おでん`を取得するためのパターン。
const RecipeRoute = new URLPattern({ pathname: "/:name" });
...

function handler(req: Request): Response {

  // HTTP requestのURLが、指定したURLPatternにマッチした情報を返す。
  // URLPatternResultという型のオブジェクトを返す。
  const match: URLPatternResult | null = RecipeRoute.exec(req.url);
  console.log("Request URL:", req.url);

  // URLPatternResultという型の構造を確認するためにコンソール出力
  console.log("Matched Route:", match);
  let name = "unknown";
  if (match) {
    name = match.pathname.groups.name ?? "おでん";
  }
  ...
}

パターンマッチング結果はURLPatternResult

マッチング結果をURLPatternResultという型のオブジェクトとして返す。
データ構造を確認するためにコンソール出力してみる。

## URLPatternResultオブジェクト
Request URL: http://localhost:8000/%E3%81%8A%E3%81%A7%E3%82%93
Matched Route: {
  inputs: [ "http://localhost:8000/%E3%81%8A%E3%81%A7%E3%82%93" ],
  protocol: { input: "http", groups: { "0": "http" } },
  username: { input: "", groups: { "0": "" } },
  password: { input: "", groups: { "0": "" } },
  hostname: { input: "localhost", groups: { "0": "localhost" } },
  port: { input: "8000", groups: { "0": "8000" } },
  pathname: {
    input: "/%E3%81%8A%E3%81%A7%E3%82%93",
    groups: { name: "%E3%81%8A%E3%81%A7%E3%82%93" }
  },
  search: { input: "", groups: { "0": "" } },
  hash: { input: "", groups: { "0": "" } }
}
  • inputs : このURLPatternに入力されたURL全体
  • protocol : URLのプロトコル部分
  • username : 昔の名残、今は使われない
  • password : 同上
  • hostname : URLのホスト名部分
  • port * URLのポート部分
  • pathname : ここ!
    • input : URLPatternに指定した:nameの部分(/から)
    • groups : nameという名前と値のペア(/は除外されている)

以下は、マッチング結果があった場合に、nameに指定された値を取得するコード。
matchは上記に記したURLPatternResultのオブジェクト。

  if (match) {
    name = match.pathname.groups.name ?? "おでん";
  }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?