コンテンツにスキップ

パスによる振り分け

wired にルーターはありません。 ハンドラーがリクエストの :path(HTTP/3 でパスを運ぶヘッダー)を読み、応答を決めます。 このページのサーバーは / と /about に応答し、それ以外のパスには本物の 404 を返します。

コード

main.c
#define WIRED_MAIN
#include "wired.h"
/* Pick the response by :path; an unknown path answers a real 404
* (wired_http_handler can choose the status, unlike the 7-argument
* handler, which always sends 200). */
static int on_request(void* ctx, wired_http_exchange* x) {
(void)ctx;
wired_span path = wired_h3req_path(x->req);
wired_dprintf(2, "request %.*s\n", WIRED_SPAN_ARG(path));
if (wired_span_eq_cstr(path, "/")) return wired_http_reply_text(x, 0, "home");
if (wired_span_eq_cstr(path, "/about"))
return wired_http_reply_text(x, 0, "about");
x->status = 404;
return 0;
}
int wired_main(int argc, char** argv) {
/* Fixed demo identity (self-signed certificate; never for production). */
static wired_srvboot_demo_keys keys;
wired_srvboot_id id;
wired_srvboot_demo(&id, &keys, 0x50, "guide-h3");
u16 port = (u16)wired_cliargs_int(argc, argv, "--port", 4433);
wired_srvrun_handler h = {.http = on_request};
wired_srvrun_obs obs = {0};
return wired_server_run(port, &id, h, obs) ? 0 : 1;
}

実行結果

Terminal window
$ ./h3-routing --port 4433
request /
request /about
request /missing
conn closed by peer (CONNECTION_CLOSE)
Terminal window
$ probe h3get 127.0.0.1:4433 / /about /missing
GET / status=200 content-type=text/plain body="home"
GET /about status=200 content-type=text/plain body="about"
GET /missing status=404 body=""
  • x->req->path と x->req->path_len がリクエストの :path を保持します。 末尾に文字列の終わりを示す NUL が付いていないので、1 バイトずつ比較します。
  • このハンドラーは、wired_srvrun_handler.http の形で wired_http_exchange* を受け取ります。 そのため、常に 200 を返す 7 引数のハンドラーと違い、x->status でステータスコードを選べます。
  • x->status を設定せずに 0 を返すと、ボディのない 200 が送られます。 返す前に x->status = 404 を設定すれば、その 404 が送られます。
  • wired_log_str は NUL 終端の文字列を必要とするので、log_request はパスをいったんローカルのバッファーにコピーします。