mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-10-09 21:03:18 +00:00
Drop the spaces between Japanese text and inline code or alphanumerics in the tour and the few other pages that still had them, and reword sentences that read awkwardly. The client compression page now lists Zstd alongside zlib and Brotli.
2.5 KiB
2.5 KiB
title, order
| title | order |
|---|---|
| Getting Started | 1 |
cpp-httplibを始めるのに必要なのは、httplib.hとC++コンパイラーだけです。ファイルをダウンロードして、Hello Worldサーバーを動かすところまでやってみましょう。
httplib.hの入手
GitHubから直接ダウンロードできます。常に最新版を使ってください。
curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
ダウンロードしたhttplib.hをプロジェクトのディレクトリに置けば、準備完了です。
コンパイラーの準備
| OS | 開発環境 | セットアップ |
|---|---|---|
| macOS | Apple Clang | Xcode Command Line Tools (xcode-select --install) |
| Ubuntu | clang++またはg++ | apt install clangまたはapt install g++ |
| Windows | MSVC | Visual Studio 2022以降(C++コンポーネントを含めてインストール) |
Hello Worldサーバー
次のコードをserver.cppとして保存しましょう。
#include "httplib.h"
int main() {
httplib::Server svr;
svr.Get("/", [](const httplib::Request&, httplib::Response& res) {
res.set_content("Hello, World!", "text/plain");
});
svr.listen("0.0.0.0", 8080);
}
たった数行で、HTTPリクエストに応答するサーバーが書けます。
コンパイルと実行
このチュートリアルのサンプルコードは、コードを簡潔に書けるC++17で書いています。cpp-httplib自体はC++11でもコンパイルできます。
# macOS
clang++ -std=c++17 -o server server.cpp
# Linux
# `-pthread`: cpp-httplibは内部でスレッドを使用
clang++ -std=c++17 -pthread -o server server.cpp
# Windows (Developer Command Prompt)
# `/EHsc`: C++例外処理を有効化
cl /EHsc /std:c++17 server.cpp
コンパイルできたら実行します。
# macOS / Linux
./server
# Windows
server.exe
ブラウザでhttp://localhost:8080を開いてください。"Hello, World!"と表示されれば成功です。
curlでも確認できます。
curl http://localhost:8080/
# Hello, World!
サーバーを停止するには、ターミナルでCtrl+Cを押します。
次のステップ
サーバーの基本がわかりましたね。次は、クライアント側を見てみましょう。cpp-httplibはHTTPクライアント機能も備えています。
次: Basic Client