Bring the READMEs and the docs pages (en and ja) in line with the current header: - Fix the client sample that does not compile, the Transfer-Encoding statement for default headers, the verifier callback comment, the thread pool spawn rule, the sanitize_filename description, and the inverted Accept-Encoding sentence. - Describe recent behaviour: TLS errors behind Read/Write failures, Host validation, Connection: close for a body without length, content_reader rules, refused CONNECT, WebSocketClient proxies, CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT, the SSE event size limit, and the payload limit of the Stream API. - Complete the API references of WebSocket, WebSocketClient and the stream:: helpers, and the SSE reconnect rules. - Fix cookbook pages: keychain loading on every backend, received Close status, a multipart sample that trusted the client's file name, an echo sample that sent binary as text, SNI, pre-request handler scope, stop() with WebSocket handlers, and the thread pool notes. - Restore the mutex in the LLM app's Chapter 5 code.
2.8 KiB
title, order, status
| title | order | status |
|---|---|---|
| S04. 静的ファイルサーバーを設定する | 23 | draft |
HTML、CSS、画像などの静的ファイルを配信したいときは、set_mount_point()を使います。URLパスとローカルディレクトリを結びつけるだけで、そのディレクトリの中身がまるごと配信されます。
基本の使い方
httplib::Server svr;
if (!svr.set_mount_point("/", "./public")) {
// ./publicが存在しない
return 1;
}
svr.listen("0.0.0.0", 8080);
set_mount_point()はディレクトリが存在しないとfalseを返すので、戻り値を確認しておきましょう。
./public/index.htmlにはhttp://localhost:8080/index.htmlで、./public/css/style.cssにはhttp://localhost:8080/css/style.cssでアクセスできます。ディレクトリ構造がそのままURLに反映されます。
ディレクトリへのリクエストには、その中のindex.htmlを返します。末尾のスラッシュがないリクエスト(/docs)は、/docs/へリダイレクト(301)されます。マウントしたディレクトリの外を指すシンボリックリンクには403を返します。
複数のマウントポイント
マウントポイントは複数登録できます。
svr.set_mount_point("/", "./public");
svr.set_mount_point("/assets", "./dist/assets");
svr.set_mount_point("/uploads", "./var/uploads");
同じパスに複数のマウントを登録することもできます。その場合は登録した順に探し、最初に見つかったファイルを返します。
APIハンドラと組み合わせる
静的ファイルとAPIハンドラは共存できます。GETとHEADのリクエストでは、まずマウントポイントからファイルを探し、見つからなければGet()などで登録したハンドラを呼びます。
svr.Get("/api/users", [](const auto &req, auto &res) {
res.set_content("[]", "application/json");
});
svr.set_mount_point("/", "./public");
これでSPAのように、/api/*はハンドラで、それ以外は./public/から配信、という構成が作れます。
MIMEタイプを追加する
拡張子からContent-Typeを決める対応表は組み込まれていますが、独自の拡張子を追加することもできます。
svr.set_file_extension_and_mimetype_mapping("wasm", "application/wasm");
Warning: 静的ファイル配信系のメソッドはスレッドセーフではありません。起動後(
listen()以降)には呼ばないでください。起動前にまとめて設定しましょう。
ダウンロード用のレスポンスを返したい場合はS06. ファイルダウンロードレスポンスを返すも参考になります。