From a058e31a3a53873e555cd06522e18aca06e71f70 Mon Sep 17 00:00:00 2001 From: yhirose Date: Thu, 5 Mar 2026 20:45:01 -0500 Subject: [PATCH] Use doc.yml to generate document site --- .github/workflows/docs.yml | 33 + docs-src/config.toml | 2 +- docs/css/main.css | 603 ------------------ docs/en/cookbook/index.html | 111 ---- docs/en/index.html | 110 ---- docs/en/tour/01-getting-started/index.html | 236 ------- docs/en/tour/02-basic-client/index.html | 529 --------------- docs/en/tour/03-basic-server/index.html | 484 -------------- docs/en/tour/04-static-file-server/index.html | 307 --------- docs/en/tour/05-tls-setup/index.html | 231 ------- docs/en/tour/06-https-client/index.html | 289 --------- docs/en/tour/07-https-server/index.html | 278 -------- docs/en/tour/08-websocket/index.html | 330 ---------- docs/en/tour/09-whats-next/index.html | 462 -------------- docs/en/tour/index.html | 143 ----- docs/favicon.svg | 4 - docs/index.html | 17 - docs/ja/cookbook/index.html | 111 ---- docs/ja/index.html | 110 ---- docs/ja/tour/01-getting-started/index.html | 236 ------- docs/ja/tour/02-basic-client/index.html | 529 --------------- docs/ja/tour/03-basic-server/index.html | 484 -------------- docs/ja/tour/04-static-file-server/index.html | 307 --------- docs/ja/tour/05-tls-setup/index.html | 231 ------- docs/ja/tour/06-https-client/index.html | 289 --------- docs/ja/tour/07-https-server/index.html | 278 -------- docs/ja/tour/08-websocket/index.html | 330 ---------- docs/ja/tour/09-whats-next/index.html | 462 -------------- docs/ja/tour/index.html | 143 ----- docs/js/main.js | 297 --------- docs/pages-data.json | 1 - 31 files changed, 34 insertions(+), 7943 deletions(-) create mode 100644 .github/workflows/docs.yml delete mode 100644 docs/css/main.css delete mode 100644 docs/en/cookbook/index.html delete mode 100644 docs/en/index.html delete mode 100644 docs/en/tour/01-getting-started/index.html delete mode 100644 docs/en/tour/02-basic-client/index.html delete mode 100644 docs/en/tour/03-basic-server/index.html delete mode 100644 docs/en/tour/04-static-file-server/index.html delete mode 100644 docs/en/tour/05-tls-setup/index.html delete mode 100644 docs/en/tour/06-https-client/index.html delete mode 100644 docs/en/tour/07-https-server/index.html delete mode 100644 docs/en/tour/08-websocket/index.html delete mode 100644 docs/en/tour/09-whats-next/index.html delete mode 100644 docs/en/tour/index.html delete mode 100644 docs/favicon.svg delete mode 100644 docs/index.html delete mode 100644 docs/ja/cookbook/index.html delete mode 100644 docs/ja/index.html delete mode 100644 docs/ja/tour/01-getting-started/index.html delete mode 100644 docs/ja/tour/02-basic-client/index.html delete mode 100644 docs/ja/tour/03-basic-server/index.html delete mode 100644 docs/ja/tour/04-static-file-server/index.html delete mode 100644 docs/ja/tour/05-tls-setup/index.html delete mode 100644 docs/ja/tour/06-https-client/index.html delete mode 100644 docs/ja/tour/07-https-server/index.html delete mode 100644 docs/ja/tour/08-websocket/index.html delete mode 100644 docs/ja/tour/09-whats-next/index.html delete mode 100644 docs/ja/tour/index.html delete mode 100644 docs/js/main.js delete mode 100644 docs/pages-data.json diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..bf553c7 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,33 @@ +name: docs +on: + push: + branches: [master] + paths: + - 'docs-src/**' +permissions: + contents: read + pages: write + id-token: write +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +jobs: + deploy: + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Install docs-gen + run: cargo install docs-gen + - name: Build + run: docs-gen build docs-src docs + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v3 + with: + path: docs + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/docs-src/config.toml b/docs-src/config.toml index a38c106..0d7e6cc 100644 --- a/docs-src/config.toml +++ b/docs-src/config.toml @@ -1,5 +1,5 @@ [system] -theme = "default" +theme = "monotone" langs = ["en", "ja"] [site] diff --git a/docs/css/main.css b/docs/css/main.css deleted file mode 100644 index ebd238e..0000000 --- a/docs/css/main.css +++ /dev/null @@ -1,603 +0,0 @@ -:root { - --bg: #333; - --bg-secondary: #3c3c3c; - --bg-code: #2a2a2a; - --text: #ccc; - --text-bright: white; - --text-muted: #999; - --text-code: #b0b0b0; - --text-inline-code: plum; - --border: #555; - --border-code: #3a3a3a; - --link: palegoldenrod; - --heading: lightskyblue; - --heading-link: #f0c090; - --header-nav-link: #ddd; - --emphasis: pink; - --nav-section: #bbb; - --nav-section-active: #ddd; - --content-width: 900px; - --sidebar-width: 280px; - --header-height: 48px; - --line-height: 1.6; -} - -* { - margin: 0; - padding: 0; - box-sizing: border-box; -} - -body { - background-color: var(--bg); - color: var(--text); - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; - line-height: var(--line-height); -} - -a { - color: var(--link); - text-decoration: none; -} - -a:hover { - text-decoration: underline; -} - -/* Header */ -.header { - position: fixed; - top: 0; - left: 0; - right: 0; - height: var(--header-height); - background-color: var(--bg-secondary); - border-bottom: 1px solid var(--border); - z-index: 100; -} - -.header-inner { - height: 100%; - display: flex; - align-items: center; - padding: 0 16px; - gap: 24px; -} - -.header-title { - color: var(--text); - font-weight: bold; - font-size: 1.1rem; - white-space: nowrap; -} - -.header-title:hover { - text-decoration: none; - color: var(--text-bright); -} - -.header-spacer { - flex: 1; -} - -.header-nav { - display: flex; - gap: 16px; -} - -.header-nav a { - display: flex; - align-items: center; - gap: 4px; - color: var(--header-nav-link); - font-size: 0.9rem; -} - -.header-nav a svg { - flex-shrink: 0; - opacity: 0.85; -} - -.header-tools { - display: flex; - align-items: center; - gap: 2px; -} - -.lang-selector { - position: relative; -} - -.lang-btn { - display: flex; - align-items: center; - gap: 5px; - background: none; - border: none; - color: var(--text); - padding: 4px 6px; - border-radius: 4px; - cursor: pointer; - font-size: 0.85rem; - opacity: 0.8; -} - -.lang-btn:hover { - opacity: 1; -} - -.lang-popup { - display: none; - position: absolute; - right: 0; - top: 100%; - margin-top: 4px; - background: var(--bg-secondary); - border: 1px solid var(--border); - border-radius: 4px; - list-style: none; - min-width: 60px; - z-index: 200; -} - -.lang-popup.open { - display: block; -} - -.lang-popup li a { - display: block; - padding: 6px 12px; - color: var(--text); - font-size: 0.85rem; -} - -.lang-popup li a:hover { - background: var(--bg); - text-decoration: none; -} - -.sidebar-toggle { - display: none; - background: none; - border: none; - color: var(--text); - font-size: 1.2rem; - cursor: pointer; - padding: 4px 8px; -} - -/* Draft banner */ -.draft-banner { - position: fixed; - top: var(--header-height); - right: 0; - background: #c44; - color: white; - padding: 4px 16px; - font-size: 0.75rem; - font-weight: bold; - letter-spacing: 0.1em; - z-index: 99; -} - -/* Layout */ -.layout { - margin-top: var(--header-height); - display: grid; - grid-template-columns: var(--sidebar-width) minmax(0, 1fr); - min-height: calc(100vh - var(--header-height)); -} - -.layout.no-sidebar { - grid-template-columns: 1fr; -} - -/* Sidebar */ -.sidebar { - width: var(--sidebar-width); - flex-shrink: 0; - padding: 24px 16px; - border-right: 1px solid var(--bg-secondary); - position: sticky; - top: var(--header-height); - height: calc(100vh - var(--header-height)); - overflow-y: auto; -} - -.nav-section { - margin-bottom: 16px; -} - -.nav-section-title { - color: var(--nav-section); - font-weight: bold; - font-size: 1.0rem; - display: block; - margin-bottom: 8px; -} - -.nav-section-title.active { - color: var(--nav-section-active); -} - -.nav-list { - list-style: none; - padding-left: 8px; -} - -.nav-list li { - margin-bottom: 4px; -} - -.nav-list li a { - color: var(--text-muted); - font-size: 0.85rem; -} - -.nav-list li a:hover { - color: var(--text); -} - -.nav-list li a.active { - color: var(--emphasis); - font-weight: bold; -} - -/* Content */ -.content { - min-width: 0; - max-width: var(--content-width); - padding: 32px 24px; - overflow-wrap: break-word; -} - -.content.portal { - max-width: var(--content-width); - padding: 48px 24px; - margin: 0 auto; -} - -.content article h1 { - font-size: 1.8rem; - margin-bottom: 24px; - color: var(--heading); -} - -.content article h2 { - font-size: 1.4rem; - margin-top: 32px; - margin-bottom: 16px; - color: var(--heading-link); -} - -.content article h3 { - font-size: 1.1rem; - margin-top: 24px; - margin-bottom: 12px; - color: var(--text); -} - -.content article p { - margin-bottom: 12px; -} - -.content article ul, -.content article ol { - margin-bottom: 12px; - padding-left: 24px; -} - -.content article li { - margin-bottom: 4px; -} - -.content article strong { - color: var(--emphasis); -} - -.content article code { - background: var(--bg-code); - color: var(--text-inline-code); - padding: 2px 6px; - border-radius: 3px; - font-size: 0.9em; -} - -.content article pre { - background: var(--bg-code); - color: var(--text-code); - padding: 16px; - border-radius: 4px; - overflow-x: auto; - margin-bottom: 16px; - border: 1px solid var(--border-code); -} - -.content article pre code { - background: none; - padding: 0; -} - -.content article table { - width: 100%; - border-collapse: collapse; - margin-bottom: 16px; -} - -.content article th, -.content article td { - border: 1px solid var(--bg-secondary); - padding: 8px 12px; - text-align: left; -} - -.content article th { - background: var(--bg-secondary); -} - -.content article blockquote { - border-left: 3px solid var(--text-muted); - padding-left: 16px; - margin-bottom: 12px; - color: var(--text-muted); -} - -/* Code block theme switching: show dark by default, swap on light mode */ -.code-block-wrapper > [data-code-theme="light"] { - display: none; -} - -html[data-theme="light"] .code-block-wrapper > [data-code-theme="dark"] { - display: none; -} - -html[data-theme="light"] .code-block-wrapper > [data-code-theme="light"] { - display: block; -} - -/* Footer */ -.footer { - padding: 8px 16px; - text-align: center; - color: var(--text-muted); - font-size: 0.8rem; - border-top: 1px solid var(--bg-secondary); -} - -/* Responsive */ -@media (max-width: 768px) { - .layout { - grid-template-columns: minmax(0, 1fr); - } - - .sidebar { - position: fixed; - left: calc(-1 * var(--sidebar-width)); - width: var(--sidebar-width); - top: var(--header-height); - height: calc(100vh - var(--header-height)); - background: var(--bg); - z-index: 50; - transition: left 0.2s ease; - border-right: 1px solid var(--border); - } - - .sidebar.open { - left: 0; - } - - .sidebar-toggle { - display: block; - } - - .content { - padding: 24px 16px; - } -} - -@media (max-width: 480px) { - :root { - --header-height: 44px; - } - - .header-inner { - padding: 0 12px; - gap: 12px; - } - - .header-nav a { - font-size: 0.8rem; - } - - .content article h1 { - font-size: 1.4rem; - } - - .content article h2 { - font-size: 1.2rem; - } -} - -/* Light mode */ -[data-theme="light"] { - --bg: #f5f5f5; - --bg-secondary: #e8e8e8; - --bg-code: #eee; - --text: #333; - --text-bright: #000; - --text-muted: #666; - --text-code: #333; - --text-inline-code: #8b5ca0; - --border: #ccc; - --border-code: #ddd; - --link: #b8860b; - --heading: #2a6496; - --heading-link: #c06020; - --header-nav-link: #282828; - --emphasis: #c04060; - --nav-section: #666; - --nav-section-active: #333; -} - -/* Theme toggle */ -.theme-toggle { - display: flex; - align-items: center; - justify-content: center; - background: none; - border: none; - color: var(--text); - padding: 5px 6px; - border-radius: 4px; - cursor: pointer; - opacity: 0.8; -} - -.theme-toggle:hover { - opacity: 1; -} - -/* Search button */ -.search-btn { - display: flex; - align-items: center; - justify-content: center; - background: none; - border: none; - color: var(--text); - padding: 5px 6px; - border-radius: 4px; - cursor: pointer; - opacity: 0.8; -} - -.search-btn:hover { - opacity: 1; -} - -/* Search overlay & modal */ -.search-overlay { - display: none; - position: fixed; - inset: 0; - background: rgba(0, 0, 0, 0.5); - z-index: 300; - justify-content: center; - align-items: flex-start; - padding-top: 12vh; -} - -.search-overlay.open { - display: flex; -} - -.search-modal { - background: var(--bg-secondary); - border: 1px solid var(--border); - border-radius: 8px; - width: 90%; - max-width: 560px; - box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4); - overflow: hidden; -} - -.search-input-wrap { - display: flex; - align-items: center; - gap: 8px; - padding: 12px 16px; - border-bottom: 1px solid var(--border); -} - -.search-input-wrap svg { - flex-shrink: 0; - opacity: 0.5; -} - -#search-input { - flex: 1; - background: none; - border: none; - outline: none; - color: var(--text-bright); - font-size: 1rem; - font-family: inherit; -} - -#search-input::placeholder { - color: var(--text-muted); -} - -.search-esc { - background: var(--bg); - color: var(--text-muted); - padding: 2px 6px; - border-radius: 3px; - font-size: 0.7rem; - border: 1px solid var(--border); -} - -.search-results { - list-style: none; - max-height: 50vh; - overflow-y: auto; - padding: 0; - margin: 0; -} - -.search-results:empty::after { - content: ""; - display: none; -} - -.search-results li { - padding: 10px 16px; - cursor: pointer; - border-bottom: 1px solid var(--border); -} - -.search-results li:last-child { - border-bottom: none; -} - -.search-results li:hover, -.search-results li.active { - background: var(--bg); -} - -.search-results li .search-result-title { - color: var(--text-bright); - font-weight: 600; - font-size: 0.9rem; - margin-bottom: 2px; -} - -.search-results li .search-result-snippet { - color: var(--text-muted); - font-size: 0.8rem; - line-height: 1.4; - overflow: hidden; - text-overflow: ellipsis; - display: -webkit-box; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; -} - -.search-results li .search-result-snippet mark { - background: rgba(255, 215, 0, 0.3); - color: var(--text-bright); - border-radius: 2px; - padding: 0 1px; -} - -[data-theme="light"] .search-results li .search-result-snippet mark { - background: rgba(255, 200, 0, 0.4); - color: var(--text); -} - -.search-no-results { - padding: 24px 16px; - text-align: center; - color: var(--text-muted); - font-size: 0.9rem; -} diff --git a/docs/en/cookbook/index.html b/docs/en/cookbook/index.html deleted file mode 100644 index 837c389..0000000 --- a/docs/en/cookbook/index.html +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - Cookbook - cpp-httplib - - - - - -
-
- cpp-httplib v0.36.0 -
- -
- - - -
- - -
- -
- -
-
- - - -
- - -
-
-

Cookbook

-

This section is under construction.

-

Check back soon for a collection of recipes organized by topic.

- -
-
- -
- - - - -
-
-
- - - ESC -
-
    -
    -
    - - - - diff --git a/docs/en/index.html b/docs/en/index.html deleted file mode 100644 index e8f2947..0000000 --- a/docs/en/index.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - cpp-httplib - cpp-httplib - - - - - -
    -
    - cpp-httplib v0.36.0 -
    - -
    - - - -
    - - -
    - -
    - -
    -
    - - - -
    - -
    -
    -

    cpp-httplib

    -

    cpp-httplib is an HTTP/HTTPS library for C++. Just copy a single header file, httplib.h, and you're ready to go.

    -

    When you need a quick HTTP server or client in C++, you want something that just works. That's exactly why I built cpp-httplib. You can start writing both servers and clients in just a few lines of code.

    -

    The API uses a lambda-based design that feels natural. It runs anywhere you have a C++11 or later compiler. Windows, macOS, Linux — use whatever environment you already have.

    -

    HTTPS works too. Just link OpenSSL or mbedTLS, and both server and client gain TLS support. Content-Encoding (gzip, Brotli, etc.), file uploads, and other features you actually need in real-world development are all included. WebSocket is also supported.

    -

    Under the hood, it uses blocking I/O with a thread pool. It's not built for handling massive numbers of simultaneous connections. But for API servers, embedded HTTP in tools, mock servers for testing, and many other use cases, it delivers solid performance.

    -

    "Solve today's problem, today." That's the kind of simplicity cpp-httplib aims for.

    -

    Documentation

    -
      -
    • A Tour of cpp-httplib — A step-by-step tutorial covering the basics. Start here if you're new
    • -
    • Cookbook — A collection of recipes organized by topic. Jump to whatever you need
    • -
    - -
    -
    - -
    - - - - -
    -
    -
    - - - ESC -
    -
      -
      -
      - - - - diff --git a/docs/en/tour/01-getting-started/index.html b/docs/en/tour/01-getting-started/index.html deleted file mode 100644 index f261f90..0000000 --- a/docs/en/tour/01-getting-started/index.html +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - Getting Started - cpp-httplib - - - - - -
      -
      - cpp-httplib v0.36.0 -
      - -
      - - - -
      - - -
      - -
      - -
      -
      - - - -
      - - -
      -
      -

      Getting Started

      -

      All you need to get started with cpp-httplib is httplib.h and a C++ compiler. Let's download the file and get a Hello World server running.

      -

      Getting httplib.h

      -

      You can download it directly from GitHub. Always use the latest version.

      -
      -curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
      -
      -
      -curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
      -
      -
      -

      Place the downloaded httplib.h in your project directory and you're good to go.

      -

      Setting Up Your Compiler

      - - - - -
      OSDevelopment EnvironmentSetup
      macOSApple ClangXcode Command Line Tools (xcode-select --install)
      Ubuntuclang++ or g++apt install clang or apt install g++
      WindowsMSVCVisual Studio 2022 or later (install with C++ components)
      -

      Hello World Server

      -

      Save the following code as 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);
      -}
      -
      -
      -#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);
      -}
      -
      -
      -

      In just a few lines, you have a server that responds to HTTP requests.

      -

      Compiling and Running

      -

      The sample code in this tutorial is written in C++17 for cleaner, more concise code. cpp-httplib itself can compile with C++11 as well.

      -
      -# macOS
      -clang++ -std=c++17 -o server server.cpp
      -
      -# Linux
      -# `-pthread`: cpp-httplib uses threads internally
      -clang++ -std=c++17 -pthread -o server server.cpp
      -
      -# Windows (Developer Command Prompt)
      -# `/EHsc`: Enable C++ exception handling
      -cl /EHsc /std:c++17 server.cpp
      -
      -
      -# macOS
      -clang++ -std=c++17 -o server server.cpp
      -
      -# Linux
      -# `-pthread`: cpp-httplib uses threads internally
      -clang++ -std=c++17 -pthread -o server server.cpp
      -
      -# Windows (Developer Command Prompt)
      -# `/EHsc`: Enable C++ exception handling
      -cl /EHsc /std:c++17 server.cpp
      -
      -
      -

      Once it compiles, run it.

      -
      -# macOS / Linux
      -./server
      -
      -# Windows
      -server.exe
      -
      -
      -# macOS / Linux
      -./server
      -
      -# Windows
      -server.exe
      -
      -
      -

      Open http://localhost:8080 in your browser. If you see "Hello, World!", you're all set.

      -

      You can also verify with curl.

      -
      -curl http://localhost:8080/
      -# Hello, World!
      -
      -
      -curl http://localhost:8080/
      -# Hello, World!
      -
      -
      -

      To stop the server, press Ctrl+C in your terminal.

      -

      Next Steps

      -

      Now you know the basics of running a server. Next, let's look at the client side. cpp-httplib also comes with HTTP client functionality.

      -

      Next: Basic Client

      - -
      -
      - -
      - - - - -
      -
      -
      - - - ESC -
      -
        -
        -
        - - - - diff --git a/docs/en/tour/02-basic-client/index.html b/docs/en/tour/02-basic-client/index.html deleted file mode 100644 index 48cab82..0000000 --- a/docs/en/tour/02-basic-client/index.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - Basic Client - cpp-httplib - - - - - -
        -
        - cpp-httplib v0.36.0 -
        - -
        - - - -
        - - -
        - -
        - -
        -
        - - - -
        - - -
        -
        -

        Basic Client

        -

        cpp-httplib isn't just for servers -- it also comes with a full HTTP client. Let's use httplib::Client to send GET and POST requests.

        -

        Preparing a Test Server

        -

        To try out the client, you need a server that accepts requests. Save the following code, then compile and run it the same way you did in the previous chapter. We'll cover the server details in the next chapter.

        -
        -#include "httplib.h"
        -#include <iostream>
        -
        -int main() {
        -    httplib::Server svr;
        -
        -    svr.Get("/hi", [](const auto &, auto &res) {
        -        res.set_content("Hello!", "text/plain");
        -    });
        -
        -    svr.Get("/search", [](const auto &req, auto &res) {
        -        auto q = req.get_param_value("q");
        -        res.set_content("Query: " + q, "text/plain");
        -    });
        -
        -    svr.Post("/post", [](const auto &req, auto &res) {
        -        res.set_content(req.body, "text/plain");
        -    });
        -
        -    svr.Post("/submit", [](const auto &req, auto &res) {
        -        std::string result;
        -        for (auto &[key, val] : req.params) {
        -            result += key + " = " + val + "\n";
        -        }
        -        res.set_content(result, "text/plain");
        -    });
        -
        -    svr.Post("/upload", [](const auto &req, auto &res) {
        -        auto f = req.form.get_file("file");
        -        auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
        -        res.set_content(content, "text/plain");
        -    });
        -
        -    svr.Get("/users/:id", [](const auto &req, auto &res) {
        -        auto id = req.path_params.at("id");
        -        res.set_content("User ID: " + id, "text/plain");
        -    });
        -
        -    svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
        -        auto id = req.matches[1];
        -        res.set_content("File ID: " + std::string(id), "text/plain");
        -    });
        -
        -    std::cout << "Listening on port 8080..." << std::endl;
        -    svr.listen("0.0.0.0", 8080);
        -}
        -
        -
        -#include "httplib.h"
        -#include <iostream>
        -
        -int main() {
        -    httplib::Server svr;
        -
        -    svr.Get("/hi", [](const auto &, auto &res) {
        -        res.set_content("Hello!", "text/plain");
        -    });
        -
        -    svr.Get("/search", [](const auto &req, auto &res) {
        -        auto q = req.get_param_value("q");
        -        res.set_content("Query: " + q, "text/plain");
        -    });
        -
        -    svr.Post("/post", [](const auto &req, auto &res) {
        -        res.set_content(req.body, "text/plain");
        -    });
        -
        -    svr.Post("/submit", [](const auto &req, auto &res) {
        -        std::string result;
        -        for (auto &[key, val] : req.params) {
        -            result += key + " = " + val + "\n";
        -        }
        -        res.set_content(result, "text/plain");
        -    });
        -
        -    svr.Post("/upload", [](const auto &req, auto &res) {
        -        auto f = req.form.get_file("file");
        -        auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
        -        res.set_content(content, "text/plain");
        -    });
        -
        -    svr.Get("/users/:id", [](const auto &req, auto &res) {
        -        auto id = req.path_params.at("id");
        -        res.set_content("User ID: " + id, "text/plain");
        -    });
        -
        -    svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
        -        auto id = req.matches[1];
        -        res.set_content("File ID: " + std::string(id), "text/plain");
        -    });
        -
        -    std::cout << "Listening on port 8080..." << std::endl;
        -    svr.listen("0.0.0.0", 8080);
        -}
        -
        -
        -

        GET Request

        -

        Once the server is running, open a separate terminal and give it a try. Let's start with the simplest GET request.

        -
        -#include "httplib.h"
        -#include <iostream>
        -
        -int main() {
        -    httplib::Client cli("http://localhost:8080");
        -
        -    auto res = cli.Get("/hi");
        -    if (res) {
        -        std::cout << res->status << std::endl;  // 200
        -        std::cout << res->body << std::endl;    // Hello!
        -    }
        -}
        -
        -
        -#include "httplib.h"
        -#include <iostream>
        -
        -int main() {
        -    httplib::Client cli("http://localhost:8080");
        -
        -    auto res = cli.Get("/hi");
        -    if (res) {
        -        std::cout << res->status << std::endl;  // 200
        -        std::cout << res->body << std::endl;    // Hello!
        -    }
        -}
        -
        -
        -

        Pass the server address to the httplib::Client constructor, then call Get() to send a request. You can retrieve the status code and body from the returned res.

        -

        Here's the equivalent curl command.

        -
        -curl http://localhost:8080/hi
        -# Hello!
        -
        -
        -curl http://localhost:8080/hi
        -# Hello!
        -
        -
        -

        Checking the Response

        -

        A response contains header information in addition to the status code and body.

        -
        -auto res = cli.Get("/hi");
        -if (res) {
        -    // Status code
        -    std::cout << res->status << std::endl;  // 200
        -
        -    // Body
        -    std::cout << res->body << std::endl;  // Hello!
        -
        -    // Headers
        -    std::cout << res->get_header_value("Content-Type") << std::endl;  // text/plain
        -}
        -
        -
        -auto res = cli.Get("/hi");
        -if (res) {
        -    // Status code
        -    std::cout << res->status << std::endl;  // 200
        -
        -    // Body
        -    std::cout << res->body << std::endl;  // Hello!
        -
        -    // Headers
        -    std::cout << res->get_header_value("Content-Type") << std::endl;  // text/plain
        -}
        -
        -
        -

        res->body is a std::string, so if you want to parse a JSON response, you can pass it directly to a JSON library like nlohmann/json.

        -

        Query Parameters

        -

        To add query parameters to a GET request, you can either write them directly in the URL or use httplib::Params.

        -
        -auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
        -if (res) {
        -    std::cout << res->body << std::endl;  // Query: cpp-httplib
        -}
        -
        -
        -auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
        -if (res) {
        -    std::cout << res->body << std::endl;  // Query: cpp-httplib
        -}
        -
        -
        -

        httplib::Params automatically URL-encodes special characters for you.

        -
        -curl "http://localhost:8080/search?q=cpp-httplib"
        -# Query: cpp-httplib
        -
        -
        -curl "http://localhost:8080/search?q=cpp-httplib"
        -# Query: cpp-httplib
        -
        -
        -

        Path Parameters

        -

        When values are embedded directly in the URL path, no special client API is needed. Just pass the path to Get() as-is.

        -
        -auto res = cli.Get("/users/42");
        -if (res) {
        -    std::cout << res->body << std::endl;  // User ID: 42
        -}
        -
        -
        -auto res = cli.Get("/users/42");
        -if (res) {
        -    std::cout << res->body << std::endl;  // User ID: 42
        -}
        -
        -
        -curl http://localhost:8080/users/42
        -# User ID: 42
        -
        -
        -curl http://localhost:8080/users/42
        -# User ID: 42
        -
        -
        -

        The test server also has a /files/(\d+) route that uses a regex to accept numeric IDs only.

        -
        -auto res = cli.Get("/files/42");
        -if (res) {
        -    std::cout << res->body << std::endl;  // File ID: 42
        -}
        -
        -
        -auto res = cli.Get("/files/42");
        -if (res) {
        -    std::cout << res->body << std::endl;  // File ID: 42
        -}
        -
        -
        -curl http://localhost:8080/files/42
        -# File ID: 42
        -
        -
        -curl http://localhost:8080/files/42
        -# File ID: 42
        -
        -
        -

        Pass a non-numeric ID like /files/abc and you'll get a 404. We'll cover how that works in the next chapter.

        -

        Request Headers

        -

        To add custom HTTP headers, pass an httplib::Headers object. This works with both Get() and Post().

        -
        -auto res = cli.Get("/hi", httplib::Headers{
        -    {"Authorization", "Bearer my-token"}
        -});
        -
        -
        -auto res = cli.Get("/hi", httplib::Headers{
        -    {"Authorization", "Bearer my-token"}
        -});
        -
        -
        -curl -H "Authorization: Bearer my-token" http://localhost:8080/hi
        -
        -
        -curl -H "Authorization: Bearer my-token" http://localhost:8080/hi
        -
        -
        -

        POST Request

        -

        Let's POST some text data. Pass the body as the second argument to Post() and the Content-Type as the third.

        -
        -auto res = cli.Post("/post", "Hello, Server!", "text/plain");
        -if (res) {
        -    std::cout << res->status << std::endl;  // 200
        -    std::cout << res->body << std::endl;    // Hello, Server!
        -}
        -
        -
        -auto res = cli.Post("/post", "Hello, Server!", "text/plain");
        -if (res) {
        -    std::cout << res->status << std::endl;  // 200
        -    std::cout << res->body << std::endl;    // Hello, Server!
        -}
        -
        -
        -

        The test server's /post endpoint echoes the body back, so you get the same string you sent.

        -
        -curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post
        -# Hello, Server!
        -
        -
        -curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post
        -# Hello, Server!
        -
        -
        -

        Sending Form Data

        -

        You can send key-value pairs just like an HTML form. Use httplib::Params for this.

        -
        -auto res = cli.Post("/submit", httplib::Params{
        -    {"name", "Alice"},
        -    {"age", "30"}
        -});
        -if (res) {
        -    std::cout << res->body << std::endl;
        -    // age = 30
        -    // name = Alice
        -}
        -
        -
        -auto res = cli.Post("/submit", httplib::Params{
        -    {"name", "Alice"},
        -    {"age", "30"}
        -});
        -if (res) {
        -    std::cout << res->body << std::endl;
        -    // age = 30
        -    // name = Alice
        -}
        -
        -
        -

        This sends the data in application/x-www-form-urlencoded format.

        -
        -curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
        -
        -
        -curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
        -
        -
        -

        POSTing a File

        -

        To upload a file, use httplib::UploadFormDataItems to send it as multipart form data.

        -
        -auto res = cli.Post("/upload", httplib::UploadFormDataItems{
        -    {"file", "Hello, File!", "hello.txt", "text/plain"}
        -});
        -if (res) {
        -    std::cout << res->body << std::endl;  // hello.txt (12 bytes)
        -}
        -
        -
        -auto res = cli.Post("/upload", httplib::UploadFormDataItems{
        -    {"file", "Hello, File!", "hello.txt", "text/plain"}
        -});
        -if (res) {
        -    std::cout << res->body << std::endl;  // hello.txt (12 bytes)
        -}
        -
        -
        -

        Each element in UploadFormDataItems has four fields: {name, content, filename, content_type}.

        -
        -curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload
        -
        -
        -curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload
        -
        -
        -

        Error Handling

        -

        Network communication can fail -- the server might not be reachable. Always check whether res is valid.

        -
        -httplib::Client cli("http://localhost:9999");  // Non-existent port
        -auto res = cli.Get("/hi");
        -
        -if (!res) {
        -    // Connection error
        -    std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
        -    // Error: Connection
        -    return 1;
        -}
        -
        -// If we reach here, we have a response
        -if (res->status != 200) {
        -    std::cout << "HTTP Error: " << res->status << std::endl;
        -    return 1;
        -}
        -
        -std::cout << res->body << std::endl;
        -
        -
        -httplib::Client cli("http://localhost:9999");  // Non-existent port
        -auto res = cli.Get("/hi");
        -
        -if (!res) {
        -    // Connection error
        -    std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
        -    // Error: Connection
        -    return 1;
        -}
        -
        -// If we reach here, we have a response
        -if (res->status != 200) {
        -    std::cout << "HTTP Error: " << res->status << std::endl;
        -    return 1;
        -}
        -
        -std::cout << res->body << std::endl;
        -
        -
        -

        There are two levels of errors.

        -
          -
        • Connection error: The client couldn't reach the server. res evaluates to false, and you can call res.error() to find out what went wrong.
        • -
        • HTTP error: The server returned an error status (404, 500, etc.). res evaluates to true, but you need to check res->status.
        • -
        -

        Next Steps

        -

        Now you know how to send requests from a client. Next, let's take a closer look at the server side. We'll dig into routing, path parameters, and more.

        -

        Next: Basic Server

        - -
        -
        - -
        - - - - -
        -
        -
        - - - ESC -
        -
          -
          -
          - - - - diff --git a/docs/en/tour/03-basic-server/index.html b/docs/en/tour/03-basic-server/index.html deleted file mode 100644 index 27bacff..0000000 --- a/docs/en/tour/03-basic-server/index.html +++ /dev/null @@ -1,484 +0,0 @@ - - - - - - Basic Server - cpp-httplib - - - - - -
          -
          - cpp-httplib v0.36.0 -
          - -
          - - - -
          - - -
          - -
          - -
          -
          - - - -
          - - -
          -
          -

          Basic Server

          -

          In the previous chapter, you sent requests from a client to a test server. Now let's walk through how that server actually works.

          -

          Starting the Server

          -

          Once you've registered your routes, call svr.listen() to start the server.

          -
          -svr.listen("0.0.0.0", 8080);
          -
          -
          -svr.listen("0.0.0.0", 8080);
          -
          -
          -

          The first argument is the host, and the second is the port. "0.0.0.0" listens on all network interfaces. Use "127.0.0.1" if you want to accept connections from your own machine only.

          -

          listen() is a blocking call. It won't return until the server stops. The server keeps running until you press Ctrl+C in your terminal or call svr.stop() from another thread.

          -

          Routing

          -

          Routing is the heart of any server. It's how you tell cpp-httplib: when a request comes in for this URL with this HTTP method, run this code.

          -
          -httplib::Server svr;
          -
          -svr.Get("/hi", [](const httplib::Request &req, httplib::Response &res) {
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -httplib::Server svr;
          -
          -svr.Get("/hi", [](const httplib::Request &req, httplib::Response &res) {
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -

          svr.Get() registers a handler for GET requests. The first argument is the path, the second is the handler function. When a GET request arrives at /hi, your lambda runs.

          -

          There's a method for each HTTP verb.

          -
          -svr.Get("/path",    handler);  // GET
          -svr.Post("/path",   handler);  // POST
          -svr.Put("/path",    handler);  // PUT
          -svr.Delete("/path", handler);  // DELETE
          -
          -
          -svr.Get("/path",    handler);  // GET
          -svr.Post("/path",   handler);  // POST
          -svr.Put("/path",    handler);  // PUT
          -svr.Delete("/path", handler);  // DELETE
          -
          -
          -

          The handler signature is (const httplib::Request &req, httplib::Response &res). You can use auto to keep it short.

          -
          -svr.Get("/hi", [](const auto &req, auto &res) {
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -svr.Get("/hi", [](const auto &req, auto &res) {
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -

          The handler only runs when the path matches. Requests to unregistered paths automatically return 404.

          -

          The Request Object

          -

          The first parameter req gives you everything the client sent.

          -

          Body

          -

          req.body holds the request body as a std::string.

          -
          -svr.Post("/post", [](const auto &req, auto &res) {
          -    // Echo the body back to the client
          -    res.set_content(req.body, "text/plain");
          -});
          -
          -
          -svr.Post("/post", [](const auto &req, auto &res) {
          -    // Echo the body back to the client
          -    res.set_content(req.body, "text/plain");
          -});
          -
          -
          -

          Headers

          -

          Use req.get_header_value() to read a request header.

          -
          -svr.Get("/check", [](const auto &req, auto &res) {
          -    auto auth = req.get_header_value("Authorization");
          -    res.set_content("Auth: " + auth, "text/plain");
          -});
          -
          -
          -svr.Get("/check", [](const auto &req, auto &res) {
          -    auto auth = req.get_header_value("Authorization");
          -    res.set_content("Auth: " + auth, "text/plain");
          -});
          -
          -
          -

          Query Parameters and Form Data

          -

          req.get_param_value() retrieves a parameter by name. It works for both GET query parameters and POST form data.

          -
          -svr.Get("/search", [](const auto &req, auto &res) {
          -    auto q = req.get_param_value("q");
          -    res.set_content("Query: " + q, "text/plain");
          -});
          -
          -
          -svr.Get("/search", [](const auto &req, auto &res) {
          -    auto q = req.get_param_value("q");
          -    res.set_content("Query: " + q, "text/plain");
          -});
          -
          -
          -

          A request to /search?q=cpp-httplib gives you "cpp-httplib" for q.

          -

          To loop over all parameters, use req.params.

          -
          -svr.Post("/submit", [](const auto &req, auto &res) {
          -    std::string result;
          -    for (auto &[key, val] : req.params) {
          -        result += key + " = " + val + "\n";
          -    }
          -    res.set_content(result, "text/plain");
          -});
          -
          -
          -svr.Post("/submit", [](const auto &req, auto &res) {
          -    std::string result;
          -    for (auto &[key, val] : req.params) {
          -        result += key + " = " + val + "\n";
          -    }
          -    res.set_content(result, "text/plain");
          -});
          -
          -
          -

          File Uploads

          -

          Files uploaded via multipart form data are available through req.form.get_file().

          -
          -svr.Post("/upload", [](const auto &req, auto &res) {
          -    auto f = req.form.get_file("file");
          -    auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
          -    res.set_content(content, "text/plain");
          -});
          -
          -
          -svr.Post("/upload", [](const auto &req, auto &res) {
          -    auto f = req.form.get_file("file");
          -    auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
          -    res.set_content(content, "text/plain");
          -});
          -
          -
          -

          f.filename gives you the filename, and f.content gives you the file data.

          -

          Path Parameters

          -

          Sometimes you want to capture part of the URL as a variable -- for example, the 42 in /users/42. Use the :param syntax to do that.

          -
          -svr.Get("/users/:id", [](const auto &req, auto &res) {
          -    auto id = req.path_params.at("id");
          -    res.set_content("User ID: " + id, "text/plain");
          -});
          -
          -
          -svr.Get("/users/:id", [](const auto &req, auto &res) {
          -    auto id = req.path_params.at("id");
          -    res.set_content("User ID: " + id, "text/plain");
          -});
          -
          -
          -

          A request to /users/42 gives you "42" from req.path_params.at("id"). /users/100 gives you "100".

          -

          You can capture multiple segments at once.

          -
          -svr.Get("/users/:user_id/posts/:post_id", [](const auto &req, auto &res) {
          -    auto user_id = req.path_params.at("user_id");
          -    auto post_id = req.path_params.at("post_id");
          -    res.set_content("User: " + user_id + ", Post: " + post_id, "text/plain");
          -});
          -
          -
          -svr.Get("/users/:user_id/posts/:post_id", [](const auto &req, auto &res) {
          -    auto user_id = req.path_params.at("user_id");
          -    auto post_id = req.path_params.at("post_id");
          -    res.set_content("User: " + user_id + ", Post: " + post_id, "text/plain");
          -});
          -
          -
          -

          Regex Patterns

          -

          You can also write a regular expression directly in the path instead of :param. Capture group values are available via req.matches, which is a std::smatch.

          -
          -// Only accept numeric IDs
          -svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
          -    auto id = req.matches[1];  // First capture group
          -    res.set_content("File ID: " + std::string(id), "text/plain");
          -});
          -
          -
          -// Only accept numeric IDs
          -svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
          -    auto id = req.matches[1];  // First capture group
          -    res.set_content("File ID: " + std::string(id), "text/plain");
          -});
          -
          -
          -

          /files/42 matches, but /files/abc doesn't. This is handy when you want to constrain what values are accepted.

          -

          Building a Response

          -

          The second parameter res is how you send data back to the client.

          -

          Body and Content-Type

          -

          res.set_content() sets the body and Content-Type. That's all you need for a 200 response.

          -
          -svr.Get("/hi", [](const auto &req, auto &res) {
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -svr.Get("/hi", [](const auto &req, auto &res) {
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -

          Status Code

          -

          To return a different status code, assign to res.status.

          -
          -svr.Get("/not-found", [](const auto &req, auto &res) {
          -    res.status = 404;
          -    res.set_content("Not found", "text/plain");
          -});
          -
          -
          -svr.Get("/not-found", [](const auto &req, auto &res) {
          -    res.status = 404;
          -    res.set_content("Not found", "text/plain");
          -});
          -
          -
          -

          Response Headers

          -

          Add response headers with res.set_header().

          -
          -svr.Get("/with-header", [](const auto &req, auto &res) {
          -    res.set_header("X-Custom", "my-value");
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -svr.Get("/with-header", [](const auto &req, auto &res) {
          -    res.set_header("X-Custom", "my-value");
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -

          Walking Through the Test Server

          -

          Now let's use what we've learned to read through the test server from the previous chapter.

          -

          GET /hi

          -
          -svr.Get("/hi", [](const auto &, auto &res) {
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -svr.Get("/hi", [](const auto &, auto &res) {
          -    res.set_content("Hello!", "text/plain");
          -});
          -
          -
          -

          The simplest possible handler. We don't need any information from the request, so the req parameter is left unnamed. It just returns "Hello!".

          -

          GET /search

          -
          -svr.Get("/search", [](const auto &req, auto &res) {
          -    auto q = req.get_param_value("q");
          -    res.set_content("Query: " + q, "text/plain");
          -});
          -
          -
          -svr.Get("/search", [](const auto &req, auto &res) {
          -    auto q = req.get_param_value("q");
          -    res.set_content("Query: " + q, "text/plain");
          -});
          -
          -
          -

          req.get_param_value("q") pulls out the query parameter q. A request to /search?q=cpp-httplib returns "Query: cpp-httplib".

          -

          POST /post

          -
          -svr.Post("/post", [](const auto &req, auto &res) {
          -    res.set_content(req.body, "text/plain");
          -});
          -
          -
          -svr.Post("/post", [](const auto &req, auto &res) {
          -    res.set_content(req.body, "text/plain");
          -});
          -
          -
          -

          An echo server. Whatever body the client sends, req.body holds it, and we send it straight back.

          -

          POST /submit

          -
          -svr.Post("/submit", [](const auto &req, auto &res) {
          -    std::string result;
          -    for (auto &[key, val] : req.params) {
          -        result += key + " = " + val + "\n";
          -    }
          -    res.set_content(result, "text/plain");
          -});
          -
          -
          -svr.Post("/submit", [](const auto &req, auto &res) {
          -    std::string result;
          -    for (auto &[key, val] : req.params) {
          -        result += key + " = " + val + "\n";
          -    }
          -    res.set_content(result, "text/plain");
          -});
          -
          -
          -

          Loops over the form data in req.params using structured bindings (auto &[key, val]) to unpack each key-value pair.

          -

          POST /upload

          -
          -svr.Post("/upload", [](const auto &req, auto &res) {
          -    auto f = req.form.get_file("file");
          -    auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
          -    res.set_content(content, "text/plain");
          -});
          -
          -
          -svr.Post("/upload", [](const auto &req, auto &res) {
          -    auto f = req.form.get_file("file");
          -    auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
          -    res.set_content(content, "text/plain");
          -});
          -
          -
          -

          Receives a file uploaded via multipart form data. req.form.get_file("file") fetches the field named "file", and we respond with the filename and size.

          -

          GET /users/:id

          -
          -svr.Get("/users/:id", [](const auto &req, auto &res) {
          -    auto id = req.path_params.at("id");
          -    res.set_content("User ID: " + id, "text/plain");
          -});
          -
          -
          -svr.Get("/users/:id", [](const auto &req, auto &res) {
          -    auto id = req.path_params.at("id");
          -    res.set_content("User ID: " + id, "text/plain");
          -});
          -
          -
          -

          :id is the path parameter. req.path_params.at("id") retrieves its value. /users/42 gives you "42", /users/alice gives you "alice".

          -

          GET /files/(\d+)

          -
          -svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
          -    auto id = req.matches[1];
          -    res.set_content("File ID: " + std::string(id), "text/plain");
          -});
          -
          -
          -svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
          -    auto id = req.matches[1];
          -    res.set_content("File ID: " + std::string(id), "text/plain");
          -});
          -
          -
          -

          The regex (\d+) matches numeric IDs only. /files/42 hits this handler, but /files/abc returns 404. req.matches[1] retrieves the first capture group.

          -

          Next Steps

          -

          You now have the full picture of how a server works. Routing, reading requests, building responses -- that's enough to build a real API server.

          -

          Next, let's look at serving static files. We'll build a server that delivers HTML and CSS.

          -

          Next: Static File Server

          - -
          -
          - -
          - - - - -
          -
          -
          - - - ESC -
          -
            -
            -
            - - - - diff --git a/docs/en/tour/04-static-file-server/index.html b/docs/en/tour/04-static-file-server/index.html deleted file mode 100644 index d6a0bbd..0000000 --- a/docs/en/tour/04-static-file-server/index.html +++ /dev/null @@ -1,307 +0,0 @@ - - - - - - Static File Server - cpp-httplib - - - - - -
            -
            - cpp-httplib v0.36.0 -
            - -
            - - - -
            - - -
            - -
            - -
            -
            - - - -
            - - -
            -
            -

            Static File Server

            -

            cpp-httplib can serve static files too — HTML, CSS, images, you name it. No complicated configuration required. One call to set_mount_point() is all it takes.

            -

            The basics of set_mount_point

            -

            Let's jump right in. set_mount_point() maps a URL path to a local directory.

            -
            -#include "httplib.h"
            -#include <iostream>
            -
            -int main() {
            -    httplib::Server svr;
            -
            -    svr.set_mount_point("/", "./html");
            -
            -    std::cout << "Listening on port 8080..." << std::endl;
            -    svr.listen("0.0.0.0", 8080);
            -}
            -
            -
            -#include "httplib.h"
            -#include <iostream>
            -
            -int main() {
            -    httplib::Server svr;
            -
            -    svr.set_mount_point("/", "./html");
            -
            -    std::cout << "Listening on port 8080..." << std::endl;
            -    svr.listen("0.0.0.0", 8080);
            -}
            -
            -
            -

            The first argument is the URL mount point. The second is the local directory path. In this example, requests to / are served from the ./html directory.

            -

            Let's try it out. First, create an html directory and add an index.html file.

            -
            -mkdir html
            -
            -
            -mkdir html
            -
            -
            -<!DOCTYPE html>
            -<html>
            -<head><title>My Page</title></head>
            -<body>
            -    <h1>Hello from cpp-httplib!</h1>
            -    <p>This is a static file.</p>
            -</body>
            -</html>
            -
            -
            -<!DOCTYPE html>
            -<html>
            -<head><title>My Page</title></head>
            -<body>
            -    <h1>Hello from cpp-httplib!</h1>
            -    <p>This is a static file.</p>
            -</body>
            -</html>
            -
            -
            -

            Compile and start the server.

            -
            -g++ -std=c++17 -o server server.cpp -pthread
            -./server
            -
            -
            -g++ -std=c++17 -o server server.cpp -pthread
            -./server
            -
            -
            -

            Open http://localhost:8080 in your browser. You should see the contents of html/index.html. Visiting http://localhost:8080/index.html returns the same page.

            -

            You can also access it with the client code from the previous chapter, or with curl.

            -
            -httplib::Client cli("http://localhost:8080");
            -auto res = cli.Get("/");
            -if (res) {
            -    std::cout << res->body << std::endl;  // HTML is displayed
            -}
            -
            -
            -httplib::Client cli("http://localhost:8080");
            -auto res = cli.Get("/");
            -if (res) {
            -    std::cout << res->body << std::endl;  // HTML is displayed
            -}
            -
            -
            -curl http://localhost:8080
            -
            -
            -curl http://localhost:8080
            -
            -
            -

            Multiple mount points

            -

            You can call set_mount_point() as many times as you like. Each URL path gets its own directory.

            -
            -svr.set_mount_point("/", "./public");
            -svr.set_mount_point("/assets", "./static/assets");
            -svr.set_mount_point("/docs", "./documentation");
            -
            -
            -svr.set_mount_point("/", "./public");
            -svr.set_mount_point("/assets", "./static/assets");
            -svr.set_mount_point("/docs", "./documentation");
            -
            -
            -

            A request to /assets/style.css serves ./static/assets/style.css. A request to /docs/guide.html serves ./documentation/guide.html.

            -

            Combining with handlers

            -

            Static file serving and routing handlers — the kind you learned about in the previous chapter — work side by side.

            -
            -httplib::Server svr;
            -
            -// API endpoint
            -svr.Get("/api/hello", [](const auto &, auto &res) {
            -    res.set_content(R"({"message":"Hello!"})", "application/json");
            -});
            -
            -// Static file serving
            -svr.set_mount_point("/", "./public");
            -
            -svr.listen("0.0.0.0", 8080);
            -
            -
            -httplib::Server svr;
            -
            -// API endpoint
            -svr.Get("/api/hello", [](const auto &, auto &res) {
            -    res.set_content(R"({"message":"Hello!"})", "application/json");
            -});
            -
            -// Static file serving
            -svr.set_mount_point("/", "./public");
            -
            -svr.listen("0.0.0.0", 8080);
            -
            -
            -

            Handlers take priority. The handler responds to /api/hello. For every other path, the server looks for a file in ./public.

            -

            Adding response headers

            -

            Pass headers as the third argument to set_mount_point() and they get attached to every static file response. This is great for cache control.

            -
            -svr.set_mount_point("/", "./public", {
            -    {"Cache-Control", "max-age=3600"}
            -});
            -
            -
            -svr.set_mount_point("/", "./public", {
            -    {"Cache-Control", "max-age=3600"}
            -});
            -
            -
            -

            With this in place, the browser caches served files for one hour.

            -

            A Dockerfile for your static file server

            -

            The cpp-httplib repository includes a Dockerfile built for static file serving. We also publish a pre-built image on Docker Hub, so you can get up and running with a single command.

            -
            -> docker run -p 8080:80 -v ./my-site:/html yhirose4dockerhub/cpp-httplib-server
            -Serving HTTP on 0.0.0.0:80
            -Mount point: / -> ./html
            -Press Ctrl+C to shutdown gracefully...
            -192.168.65.1 - - [22/Feb/2026:12:00:00 +0000] "GET / HTTP/1.1" 200 256 "-" "Mozilla/5.0 ..."
            -192.168.65.1 - - [22/Feb/2026:12:00:00 +0000] "GET /style.css HTTP/1.1" 200 1024 "-" "Mozilla/5.0 ..."
            -192.168.65.1 - - [22/Feb/2026:12:00:01 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
            -
            -
            -> docker run -p 8080:80 -v ./my-site:/html yhirose4dockerhub/cpp-httplib-server
            -Serving HTTP on 0.0.0.0:80
            -Mount point: / -> ./html
            -Press Ctrl+C to shutdown gracefully...
            -192.168.65.1 - - [22/Feb/2026:12:00:00 +0000] "GET / HTTP/1.1" 200 256 "-" "Mozilla/5.0 ..."
            -192.168.65.1 - - [22/Feb/2026:12:00:00 +0000] "GET /style.css HTTP/1.1" 200 1024 "-" "Mozilla/5.0 ..."
            -192.168.65.1 - - [22/Feb/2026:12:00:01 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
            -
            -
            -

            Everything in your ./my-site directory gets served on port 8080. The access log follows the same format as NGINX, so you can see exactly what's happening.

            -

            What's next

            -

            You can now serve static files. A web server that delivers HTML, CSS, and JavaScript — built with this little code.

            -

            Next, let's encrypt your connections with HTTPS. We'll start by setting up a TLS library.

            -

            Next: TLS Setup

            - -
            -
            - -
            - - - - -
            -
            -
            - - - ESC -
            -
              -
              -
              - - - - diff --git a/docs/en/tour/05-tls-setup/index.html b/docs/en/tour/05-tls-setup/index.html deleted file mode 100644 index 1819f56..0000000 --- a/docs/en/tour/05-tls-setup/index.html +++ /dev/null @@ -1,231 +0,0 @@ - - - - - - TLS Setup - cpp-httplib - - - - - -
              -
              - cpp-httplib v0.36.0 -
              - -
              - - - -
              - - -
              - -
              - -
              -
              - - - -
              - - -
              -
              -

              TLS Setup

              -

              So far we've been using plain HTTP, but in the real world, HTTPS is the norm. To use HTTPS with cpp-httplib, you need a TLS library.

              -

              In this tour, we'll use OpenSSL. It's the most widely used option, and you'll find plenty of resources online.

              -

              Installing OpenSSL

              -

              Install it for your OS.

              - - - - -
              OSHow to install
              macOSHomebrew (brew install openssl)
              Ubuntu / Debiansudo apt install libssl-dev
              Windowsvcpkg (vcpkg install openssl)
              -

              Compile Options

              -

              To enable TLS, define the CPPHTTPLIB_OPENSSL_SUPPORT macro when compiling. You'll need a few extra options compared to the previous chapters.

              -
              -# macOS (Homebrew)
              -clang++ -std=c++17 -DCPPHTTPLIB_OPENSSL_SUPPORT \
              -    -I$(brew --prefix openssl)/include \
              -    -L$(brew --prefix openssl)/lib \
              -    -lssl -lcrypto \
              -    -framework CoreFoundation -framework Security \
              -    -o server server.cpp
              -
              -# Linux
              -clang++ -std=c++17 -pthread -DCPPHTTPLIB_OPENSSL_SUPPORT \
              -    -lssl -lcrypto \
              -    -o server server.cpp
              -
              -# Windows (Developer Command Prompt)
              -cl /EHsc /std:c++17 /DCPPHTTPLIB_OPENSSL_SUPPORT server.cpp libssl.lib libcrypto.lib
              -
              -
              -# macOS (Homebrew)
              -clang++ -std=c++17 -DCPPHTTPLIB_OPENSSL_SUPPORT \
              -    -I$(brew --prefix openssl)/include \
              -    -L$(brew --prefix openssl)/lib \
              -    -lssl -lcrypto \
              -    -framework CoreFoundation -framework Security \
              -    -o server server.cpp
              -
              -# Linux
              -clang++ -std=c++17 -pthread -DCPPHTTPLIB_OPENSSL_SUPPORT \
              -    -lssl -lcrypto \
              -    -o server server.cpp
              -
              -# Windows (Developer Command Prompt)
              -cl /EHsc /std:c++17 /DCPPHTTPLIB_OPENSSL_SUPPORT server.cpp libssl.lib libcrypto.lib
              -
              -
              -

              Let's look at what each option does.

              -
                -
              • -DCPPHTTPLIB_OPENSSL_SUPPORT — Defines the macro that enables TLS support
              • -
              • -lssl -lcrypto — Links the OpenSSL libraries
              • -
              • -I / -L (macOS only) — Points to the Homebrew OpenSSL paths
              • -
              • -framework CoreFoundation -framework Security (macOS only) — Needed to automatically load system certificates from the Keychain
              • -
              -

              Verifying the Setup

              -

              Let's make sure everything works. Here's a simple program that passes an HTTPS URL to httplib::Client.

              -
              -#define CPPHTTPLIB_OPENSSL_SUPPORT
              -#include "httplib.h"
              -#include <iostream>
              -
              -int main() {
              -    httplib::Client cli("https://www.google.com");
              -
              -    auto res = cli.Get("/");
              -    if (res) {
              -        std::cout << "Status: " << res->status << std::endl;
              -    } else {
              -        std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
              -    }
              -}
              -
              -
              -#define CPPHTTPLIB_OPENSSL_SUPPORT
              -#include "httplib.h"
              -#include <iostream>
              -
              -int main() {
              -    httplib::Client cli("https://www.google.com");
              -
              -    auto res = cli.Get("/");
              -    if (res) {
              -        std::cout << "Status: " << res->status << std::endl;
              -    } else {
              -        std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
              -    }
              -}
              -
              -
              -

              Compile and run it. If you see Status: 200, your setup is complete.

              -

              Other TLS Backends

              -

              cpp-httplib also supports Mbed TLS and wolfSSL in addition to OpenSSL. You can switch between them just by changing the macro definition and linked libraries.

              - - - - -
              BackendMacroLibraries to link
              OpenSSLCPPHTTPLIB_OPENSSL_SUPPORTlibssl, libcrypto
              Mbed TLSCPPHTTPLIB_MBEDTLS_SUPPORTlibmbedtls, libmbedx509, libmbedcrypto
              wolfSSLCPPHTTPLIB_WOLFSSL_SUPPORTlibwolfssl
              -

              This tour assumes OpenSSL, but the API is the same regardless of which backend you choose.

              -

              Next Step

              -

              You're all set with TLS. Next, let's send a request to an HTTPS site.

              -

              Next: HTTPS Client

              - -
              -
              - -
              - - - - -
              -
              -
              - - - ESC -
              -
                -
                -
                - - - - diff --git a/docs/en/tour/06-https-client/index.html b/docs/en/tour/06-https-client/index.html deleted file mode 100644 index a13ffb8..0000000 --- a/docs/en/tour/06-https-client/index.html +++ /dev/null @@ -1,289 +0,0 @@ - - - - - - HTTPS Client - cpp-httplib - - - - - -
                -
                - cpp-httplib v0.36.0 -
                - -
                - - - -
                - - -
                - -
                - -
                -
                - - - -
                - - -
                -
                -

                HTTPS Client

                -

                In the previous chapter, you set up OpenSSL. Now let's put it to use with an HTTPS client. You can use the same httplib::Client from Chapter 2. Just pass a URL with the https:// scheme to the constructor.

                -

                GET Request

                -

                Let's try accessing a real HTTPS site.

                -
                -#define CPPHTTPLIB_OPENSSL_SUPPORT
                -#include "httplib.h"
                -#include <iostream>
                -
                -int main() {
                -    httplib::Client cli("https://nghttp2.org");
                -
                -    auto res = cli.Get("/");
                -    if (res) {
                -        std::cout << res->status << std::endl;           // 200
                -        std::cout << res->body.substr(0, 100) << std::endl;  // First 100 chars of the HTML
                -    } else {
                -        std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
                -    }
                -}
                -
                -
                -#define CPPHTTPLIB_OPENSSL_SUPPORT
                -#include "httplib.h"
                -#include <iostream>
                -
                -int main() {
                -    httplib::Client cli("https://nghttp2.org");
                -
                -    auto res = cli.Get("/");
                -    if (res) {
                -        std::cout << res->status << std::endl;           // 200
                -        std::cout << res->body.substr(0, 100) << std::endl;  // First 100 chars of the HTML
                -    } else {
                -        std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
                -    }
                -}
                -
                -
                -

                In Chapter 2, you wrote httplib::Client cli("http://localhost:8080"). All you need to change is the scheme to https://. Every API you learned in Chapter 2 -- Get(), Post(), and so on -- works exactly the same way.

                -
                -curl https://nghttp2.org/
                -
                -
                -curl https://nghttp2.org/
                -
                -
                -

                Specifying a Port

                -

                The default port for HTTPS is 443. If you need a different port, include it in the URL.

                -
                -httplib::Client cli("https://localhost:8443");
                -
                -
                -httplib::Client cli("https://localhost:8443");
                -
                -
                -

                CA Certificate Verification

                -

                When connecting over HTTPS, httplib::Client verifies the server certificate by default. It only connects to servers whose certificate was issued by a trusted CA (Certificate Authority).

                -

                CA certificates are loaded automatically from the Keychain on macOS, the system CA certificate store on Linux, and the Windows certificate store on Windows. In most cases, no extra configuration is needed.

                -

                Specifying a CA Certificate File

                -

                On some environments, the system CA certificates may not be found. In that case, use set_ca_cert_path() to specify the path directly.

                -
                -httplib::Client cli("https://nghttp2.org");
                -cli.set_ca_cert_path("/etc/ssl/certs/ca-certificates.crt");
                -
                -auto res = cli.Get("/");
                -
                -
                -httplib::Client cli("https://nghttp2.org");
                -cli.set_ca_cert_path("/etc/ssl/certs/ca-certificates.crt");
                -
                -auto res = cli.Get("/");
                -
                -
                -curl --cacert /etc/ssl/certs/ca-certificates.crt https://nghttp2.org/
                -
                -
                -curl --cacert /etc/ssl/certs/ca-certificates.crt https://nghttp2.org/
                -
                -
                -

                Disabling Certificate Verification

                -

                During development, you might want to connect to a server with a self-signed certificate. You can disable verification for that.

                -
                -httplib::Client cli("https://localhost:8443");
                -cli.enable_server_certificate_verification(false);
                -
                -auto res = cli.Get("/");
                -
                -
                -httplib::Client cli("https://localhost:8443");
                -cli.enable_server_certificate_verification(false);
                -
                -auto res = cli.Get("/");
                -
                -
                -curl -k https://localhost:8443/
                -
                -
                -curl -k https://localhost:8443/
                -
                -
                -

                Never disable this in production. It opens you up to man-in-the-middle attacks.

                -

                Following Redirects

                -

                When accessing HTTPS sites, you'll often encounter redirects. For example, http:// to https://, or a bare domain to www.

                -

                By default, redirects are not followed. You can check the redirect target in the Location header.

                -
                -httplib::Client cli("https://nghttp2.org");
                -
                -auto res = cli.Get("/httpbin/redirect/3");
                -if (res) {
                -    std::cout << res->status << std::endl;  // 302
                -    std::cout << res->get_header_value("Location") << std::endl;
                -}
                -
                -
                -httplib::Client cli("https://nghttp2.org");
                -
                -auto res = cli.Get("/httpbin/redirect/3");
                -if (res) {
                -    std::cout << res->status << std::endl;  // 302
                -    std::cout << res->get_header_value("Location") << std::endl;
                -}
                -
                -
                -curl https://nghttp2.org/httpbin/redirect/3
                -
                -
                -curl https://nghttp2.org/httpbin/redirect/3
                -
                -
                -

                Call set_follow_location(true) to automatically follow redirects and get the final response.

                -
                -httplib::Client cli("https://nghttp2.org");
                -cli.set_follow_location(true);
                -
                -auto res = cli.Get("/httpbin/redirect/3");
                -if (res) {
                -    std::cout << res->status << std::endl;  // 200 (the final response)
                -}
                -
                -
                -httplib::Client cli("https://nghttp2.org");
                -cli.set_follow_location(true);
                -
                -auto res = cli.Get("/httpbin/redirect/3");
                -if (res) {
                -    std::cout << res->status << std::endl;  // 200 (the final response)
                -}
                -
                -
                -curl -L https://nghttp2.org/httpbin/redirect/3
                -
                -
                -curl -L https://nghttp2.org/httpbin/redirect/3
                -
                -
                -

                Next Steps

                -

                Now you know how to use the HTTPS client. Next, let's set up your own HTTPS server. We'll start with creating a self-signed certificate.

                -

                Next: HTTPS Server

                - -
                -
                - -
                - - - - -
                -
                -
                - - - ESC -
                -
                  -
                  -
                  - - - - diff --git a/docs/en/tour/07-https-server/index.html b/docs/en/tour/07-https-server/index.html deleted file mode 100644 index 14c97bb..0000000 --- a/docs/en/tour/07-https-server/index.html +++ /dev/null @@ -1,278 +0,0 @@ - - - - - - HTTPS Server - cpp-httplib - - - - - -
                  -
                  - cpp-httplib v0.36.0 -
                  - -
                  - - - -
                  - - -
                  - -
                  - -
                  -
                  - - - -
                  - - -
                  -
                  -

                  HTTPS Server

                  -

                  In the previous chapter, you used an HTTPS client. Now let's set up your own HTTPS server. Just swap httplib::Server from Chapter 3 with httplib::SSLServer.

                  -

                  A TLS server needs a server certificate and a private key, though. Let's get those ready first.

                  -

                  Creating a Self-Signed Certificate

                  -

                  For development and testing, a self-signed certificate works just fine. You can generate one quickly with an OpenSSL command.

                  -
                  -openssl req -x509 -noenc -keyout key.pem -out cert.pem -subj /CN=localhost
                  -
                  -
                  -openssl req -x509 -noenc -keyout key.pem -out cert.pem -subj /CN=localhost
                  -
                  -
                  -

                  This creates two files:

                  -
                    -
                  • cert.pem — Server certificate
                  • -
                  • key.pem — Private key
                  • -
                  -

                  A Minimal HTTPS Server

                  -

                  Once you have your certificate, let's write the server.

                  -
                  -#define CPPHTTPLIB_OPENSSL_SUPPORT
                  -#include "httplib.h"
                  -#include <iostream>
                  -
                  -int main() {
                  -    httplib::SSLServer svr("cert.pem", "key.pem");
                  -
                  -    svr.Get("/", [](const auto &, auto &res) {
                  -        res.set_content("Hello, HTTPS!", "text/plain");
                  -    });
                  -
                  -    std::cout << "Listening on https://localhost:8443" << std::endl;
                  -    svr.listen("0.0.0.0", 8443);
                  -}
                  -
                  -
                  -#define CPPHTTPLIB_OPENSSL_SUPPORT
                  -#include "httplib.h"
                  -#include <iostream>
                  -
                  -int main() {
                  -    httplib::SSLServer svr("cert.pem", "key.pem");
                  -
                  -    svr.Get("/", [](const auto &, auto &res) {
                  -        res.set_content("Hello, HTTPS!", "text/plain");
                  -    });
                  -
                  -    std::cout << "Listening on https://localhost:8443" << std::endl;
                  -    svr.listen("0.0.0.0", 8443);
                  -}
                  -
                  -
                  -

                  Just pass the certificate and private key paths to the httplib::SSLServer constructor. The routing API is exactly the same as httplib::Server from Chapter 3.

                  -

                  Compile and start it up.

                  -

                  Testing It Out

                  -

                  With the server running, try accessing it with curl. Since we're using a self-signed certificate, add the -k option to skip certificate verification.

                  -
                  -curl -k https://localhost:8443/
                  -# Hello, HTTPS!
                  -
                  -
                  -curl -k https://localhost:8443/
                  -# Hello, HTTPS!
                  -
                  -
                  -

                  If you open https://localhost:8443 in a browser, you'll see a "This connection is not secure" warning. That's expected with a self-signed certificate. Just proceed past it.

                  -

                  Connecting from a Client

                  -

                  Let's connect using httplib::Client from the previous chapter. There are two ways to connect to a server with a self-signed certificate.

                  -

                  Option 1: Disable Certificate Verification

                  -

                  This is the quick and easy approach for development.

                  -
                  -#define CPPHTTPLIB_OPENSSL_SUPPORT
                  -#include "httplib.h"
                  -#include <iostream>
                  -
                  -int main() {
                  -    httplib::Client cli("https://localhost:8443");
                  -    cli.enable_server_certificate_verification(false);
                  -
                  -    auto res = cli.Get("/");
                  -    if (res) {
                  -        std::cout << res->body << std::endl;  // Hello, HTTPS!
                  -    }
                  -}
                  -
                  -
                  -#define CPPHTTPLIB_OPENSSL_SUPPORT
                  -#include "httplib.h"
                  -#include <iostream>
                  -
                  -int main() {
                  -    httplib::Client cli("https://localhost:8443");
                  -    cli.enable_server_certificate_verification(false);
                  -
                  -    auto res = cli.Get("/");
                  -    if (res) {
                  -        std::cout << res->body << std::endl;  // Hello, HTTPS!
                  -    }
                  -}
                  -
                  -
                  -

                  Option 2: Specify the Self-Signed Certificate as a CA Certificate

                  -

                  This is the safer approach. You tell the client to trust cert.pem as a CA certificate.

                  -
                  -#define CPPHTTPLIB_OPENSSL_SUPPORT
                  -#include "httplib.h"
                  -#include <iostream>
                  -
                  -int main() {
                  -    httplib::Client cli("https://localhost:8443");
                  -    cli.set_ca_cert_path("cert.pem");
                  -
                  -    auto res = cli.Get("/");
                  -    if (res) {
                  -        std::cout << res->body << std::endl;  // Hello, HTTPS!
                  -    }
                  -}
                  -
                  -
                  -#define CPPHTTPLIB_OPENSSL_SUPPORT
                  -#include "httplib.h"
                  -#include <iostream>
                  -
                  -int main() {
                  -    httplib::Client cli("https://localhost:8443");
                  -    cli.set_ca_cert_path("cert.pem");
                  -
                  -    auto res = cli.Get("/");
                  -    if (res) {
                  -        std::cout << res->body << std::endl;  // Hello, HTTPS!
                  -    }
                  -}
                  -
                  -
                  -

                  This way, only connections to the server with that specific certificate are allowed, preventing impersonation. Use this approach whenever possible, even in test environments.

                  -

                  Comparing Server and SSLServer

                  -

                  The httplib::Server API you learned in Chapter 3 works exactly the same with httplib::SSLServer. The only difference is the constructor.

                  - - - - - -
                  httplib::Serverhttplib::SSLServer
                  ConstructorNo argumentsCertificate and private key paths
                  ProtocolHTTPHTTPS
                  Port (convention)80808443
                  RoutingSameSame
                  -

                  To switch an HTTP server to HTTPS, just change the constructor.

                  -

                  Next Steps

                  -

                  Your HTTPS server is up and running. You now have the basics of both HTTP/HTTPS clients and servers covered.

                  -

                  Next, let's look at the WebSocket support that was recently added to cpp-httplib.

                  -

                  Next: WebSocket

                  - -
                  -
                  - -
                  - - - - -
                  -
                  -
                  - - - ESC -
                  -
                    -
                    -
                    - - - - diff --git a/docs/en/tour/08-websocket/index.html b/docs/en/tour/08-websocket/index.html deleted file mode 100644 index 5b13259..0000000 --- a/docs/en/tour/08-websocket/index.html +++ /dev/null @@ -1,330 +0,0 @@ - - - - - - WebSocket - cpp-httplib - - - - - -
                    -
                    - cpp-httplib v0.36.0 -
                    - -
                    - - - -
                    - - -
                    - -
                    - -
                    -
                    - - - -
                    - - -
                    -
                    -

                    WebSocket

                    -

                    cpp-httplib supports WebSocket as well. Unlike HTTP request/response, WebSocket lets the server and client exchange messages in both directions. It's great for chat apps and real-time notifications.

                    -

                    Let's build an echo server and client right away.

                    -

                    Echo Server

                    -

                    Here's an echo server that sends back whatever message it receives.

                    -
                    -#include "httplib.h"
                    -#include <iostream>
                    -
                    -int main() {
                    -    httplib::Server svr;
                    -
                    -    svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                    -        std::string msg;
                    -        while (ws.read(msg)) {
                    -            ws.send(msg);  // Send back the received message as-is
                    -        }
                    -    });
                    -
                    -    std::cout << "Listening on port 8080..." << std::endl;
                    -    svr.listen("0.0.0.0", 8080);
                    -}
                    -
                    -
                    -#include "httplib.h"
                    -#include <iostream>
                    -
                    -int main() {
                    -    httplib::Server svr;
                    -
                    -    svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                    -        std::string msg;
                    -        while (ws.read(msg)) {
                    -            ws.send(msg);  // Send back the received message as-is
                    -        }
                    -    });
                    -
                    -    std::cout << "Listening on port 8080..." << std::endl;
                    -    svr.listen("0.0.0.0", 8080);
                    -}
                    -
                    -
                    -

                    You register a WebSocket handler with svr.WebSocket(). It works just like svr.Get() and svr.Post() from Chapter 3.

                    -

                    Inside the handler, ws.read(msg) waits for a message. When the connection closes, read() returns false, so the loop exits. ws.send(msg) sends a message back.

                    -

                    Connecting from a Client

                    -

                    Let's connect to the server using httplib::ws::WebSocketClient.

                    -
                    -#include "httplib.h"
                    -#include <iostream>
                    -
                    -int main() {
                    -    httplib::ws::WebSocketClient client("ws://localhost:8080/ws");
                    -
                    -    if (!client.connect()) {
                    -        std::cout << "Connection failed" << std::endl;
                    -        return 1;
                    -    }
                    -
                    -    // Send a message
                    -    client.send("Hello, WebSocket!");
                    -
                    -    // Receive a response from the server
                    -    std::string msg;
                    -    if (client.read(msg)) {
                    -        std::cout << msg << std::endl;  // Hello, WebSocket!
                    -    }
                    -
                    -    client.close();
                    -}
                    -
                    -
                    -#include "httplib.h"
                    -#include <iostream>
                    -
                    -int main() {
                    -    httplib::ws::WebSocketClient client("ws://localhost:8080/ws");
                    -
                    -    if (!client.connect()) {
                    -        std::cout << "Connection failed" << std::endl;
                    -        return 1;
                    -    }
                    -
                    -    // Send a message
                    -    client.send("Hello, WebSocket!");
                    -
                    -    // Receive a response from the server
                    -    std::string msg;
                    -    if (client.read(msg)) {
                    -        std::cout << msg << std::endl;  // Hello, WebSocket!
                    -    }
                    -
                    -    client.close();
                    -}
                    -
                    -
                    -

                    Pass a URL in ws://host:port/path format to the constructor. Call connect() to start the connection, then use send() and read() to exchange messages.

                    -

                    Text and Binary

                    -

                    WebSocket has two types of messages: text and binary. You can tell them apart by the return value of read().

                    -
                    -svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                    -    std::string msg;
                    -    httplib::ws::ReadResult ret;
                    -    while ((ret = ws.read(msg))) {
                    -        if (ret == httplib::ws::Binary) {
                    -            ws.send(msg.data(), msg.size());  // Send as binary
                    -        } else {
                    -            ws.send(msg);  // Send as text
                    -        }
                    -    }
                    -});
                    -
                    -
                    -svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                    -    std::string msg;
                    -    httplib::ws::ReadResult ret;
                    -    while ((ret = ws.read(msg))) {
                    -        if (ret == httplib::ws::Binary) {
                    -            ws.send(msg.data(), msg.size());  // Send as binary
                    -        } else {
                    -            ws.send(msg);  // Send as text
                    -        }
                    -    }
                    -});
                    -
                    -
                    -
                      -
                    • ws.send(const std::string &) — sends as a text message
                    • -
                    • ws.send(const char *, size_t) — sends as a binary message
                    • -
                    -

                    The client-side API is the same.

                    -

                    Accessing Request Information

                    -

                    You can read HTTP request information from the handshake through the first argument req in the handler. This is handy for checking authentication tokens.

                    -
                    -svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws) {
                    -    auto token = req.get_header_value("Authorization");
                    -    if (token.empty()) {
                    -        ws.close(httplib::ws::CloseStatus::PolicyViolation, "unauthorized");
                    -        return;
                    -    }
                    -
                    -    std::string msg;
                    -    while (ws.read(msg)) {
                    -        ws.send(msg);
                    -    }
                    -});
                    -
                    -
                    -svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws) {
                    -    auto token = req.get_header_value("Authorization");
                    -    if (token.empty()) {
                    -        ws.close(httplib::ws::CloseStatus::PolicyViolation, "unauthorized");
                    -        return;
                    -    }
                    -
                    -    std::string msg;
                    -    while (ws.read(msg)) {
                    -        ws.send(msg);
                    -    }
                    -});
                    -
                    -
                    -

                    Using WSS

                    -

                    WebSocket over HTTPS (WSS) is also supported. On the server side, just register a WebSocket handler on httplib::SSLServer.

                    -
                    -httplib::SSLServer svr("cert.pem", "key.pem");
                    -
                    -svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                    -    std::string msg;
                    -    while (ws.read(msg)) {
                    -        ws.send(msg);
                    -    }
                    -});
                    -
                    -svr.listen("0.0.0.0", 8443);
                    -
                    -
                    -httplib::SSLServer svr("cert.pem", "key.pem");
                    -
                    -svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                    -    std::string msg;
                    -    while (ws.read(msg)) {
                    -        ws.send(msg);
                    -    }
                    -});
                    -
                    -svr.listen("0.0.0.0", 8443);
                    -
                    -
                    -

                    On the client side, use the wss:// scheme.

                    -
                    -httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
                    -
                    -
                    -httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
                    -
                    -
                    -

                    Next Steps

                    -

                    Now you know the basics of WebSocket. This wraps up the Tour.

                    -

                    The next page gives you a summary of features we didn't cover in the Tour.

                    -

                    Next: What's Next

                    - -
                    -
                    - -
                    - - - - -
                    -
                    -
                    - - - ESC -
                    -
                      -
                      -
                      - - - - diff --git a/docs/en/tour/09-whats-next/index.html b/docs/en/tour/09-whats-next/index.html deleted file mode 100644 index 6641b85..0000000 --- a/docs/en/tour/09-whats-next/index.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - What's Next - cpp-httplib - - - - - -
                      -
                      - cpp-httplib v0.36.0 -
                      - -
                      - - - -
                      - - -
                      - -
                      - -
                      -
                      - - - -
                      - - -
                      -
                      -

                      What's Next

                      -

                      Great job finishing the Tour! You now have a solid grasp of the cpp-httplib basics. But there's a lot more to explore. Here's a quick overview of features we didn't cover in the Tour, organized by category.

                      -

                      Streaming API

                      -

                      When you're working with LLM streaming responses or downloading large files, you don't want to load the entire response into memory. Use stream::Get() to process data chunk by chunk.

                      -
                      -httplib::Client cli("http://localhost:11434");
                      -
                      -auto result = httplib::stream::Get(cli, "/api/generate");
                      -
                      -if (result) {
                      -    while (result.next()) {
                      -        std::cout.write(result.data(), result.size());
                      -    }
                      -}
                      -
                      -
                      -httplib::Client cli("http://localhost:11434");
                      -
                      -auto result = httplib::stream::Get(cli, "/api/generate");
                      -
                      -if (result) {
                      -    while (result.next()) {
                      -        std::cout.write(result.data(), result.size());
                      -    }
                      -}
                      -
                      -
                      -

                      You can also pass a content_receiver callback to Get(). This approach works with Keep-Alive.

                      -
                      -httplib::Client cli("http://localhost:8080");
                      -
                      -cli.Get("/stream", [](const char *data, size_t len) {
                      -    std::cout.write(data, len);
                      -    return true;
                      -});
                      -
                      -
                      -httplib::Client cli("http://localhost:8080");
                      -
                      -cli.Get("/stream", [](const char *data, size_t len) {
                      -    std::cout.write(data, len);
                      -    return true;
                      -});
                      -
                      -
                      -

                      On the server side, you have set_content_provider() and set_chunked_content_provider(). Use the former when you know the size, and the latter when you don't.

                      -
                      -// With known size (sets Content-Length)
                      -svr.Get("/file", [](const auto &, auto &res) {
                      -    auto size = get_file_size("large.bin");
                      -    res.set_content_provider(size, "application/octet-stream",
                      -        [](size_t offset, size_t length, httplib::DataSink &sink) {
                      -            // Send 'length' bytes starting from 'offset'
                      -            return true;
                      -        });
                      -});
                      -
                      -// Unknown size (Chunked Transfer Encoding)
                      -svr.Get("/stream", [](const auto &, auto &res) {
                      -    res.set_chunked_content_provider("text/plain",
                      -        [](size_t offset, httplib::DataSink &sink) {
                      -            sink.write("chunk\n", 6);
                      -            return true;  // Return false to finish
                      -        });
                      -});
                      -
                      -
                      -// With known size (sets Content-Length)
                      -svr.Get("/file", [](const auto &, auto &res) {
                      -    auto size = get_file_size("large.bin");
                      -    res.set_content_provider(size, "application/octet-stream",
                      -        [](size_t offset, size_t length, httplib::DataSink &sink) {
                      -            // Send 'length' bytes starting from 'offset'
                      -            return true;
                      -        });
                      -});
                      -
                      -// Unknown size (Chunked Transfer Encoding)
                      -svr.Get("/stream", [](const auto &, auto &res) {
                      -    res.set_chunked_content_provider("text/plain",
                      -        [](size_t offset, httplib::DataSink &sink) {
                      -            sink.write("chunk\n", 6);
                      -            return true;  // Return false to finish
                      -        });
                      -});
                      -
                      -
                      -

                      For uploading large files, make_file_provider() comes in handy. It streams the file instead of loading it all into memory.

                      -
                      -httplib::Client cli("http://localhost:8080");
                      -
                      -auto res = cli.Post("/upload", {}, {
                      -    httplib::make_file_provider("file", "/path/to/large-file.zip")
                      -});
                      -
                      -
                      -httplib::Client cli("http://localhost:8080");
                      -
                      -auto res = cli.Post("/upload", {}, {
                      -    httplib::make_file_provider("file", "/path/to/large-file.zip")
                      -});
                      -
                      -
                      -

                      Server-Sent Events (SSE)

                      -

                      We provide an SSE client as well. It supports automatic reconnection and resuming via Last-Event-ID.

                      -
                      -httplib::Client cli("http://localhost:8080");
                      -httplib::sse::SSEClient sse(cli, "/events");
                      -
                      -sse.on_message([](const httplib::sse::SSEMessage &msg) {
                      -    std::cout << msg.event << ": " << msg.data << std::endl;
                      -});
                      -
                      -sse.start();  // Blocking, with auto-reconnection
                      -
                      -
                      -httplib::Client cli("http://localhost:8080");
                      -httplib::sse::SSEClient sse(cli, "/events");
                      -
                      -sse.on_message([](const httplib::sse::SSEMessage &msg) {
                      -    std::cout << msg.event << ": " << msg.data << std::endl;
                      -});
                      -
                      -sse.start();  // Blocking, with auto-reconnection
                      -
                      -
                      -

                      You can also set separate handlers for each event type.

                      -
                      -sse.on_event("update", [](const httplib::sse::SSEMessage &msg) {
                      -    // Only handles "update" events
                      -});
                      -
                      -
                      -sse.on_event("update", [](const httplib::sse::SSEMessage &msg) {
                      -    // Only handles "update" events
                      -});
                      -
                      -
                      -

                      Authentication

                      -

                      The client has helpers for Basic auth, Bearer Token auth, and Digest auth.

                      -
                      -httplib::Client cli("https://api.example.com");
                      -cli.set_basic_auth("user", "password");
                      -cli.set_bearer_token_auth("my-token");
                      -
                      -
                      -httplib::Client cli("https://api.example.com");
                      -cli.set_basic_auth("user", "password");
                      -cli.set_bearer_token_auth("my-token");
                      -
                      -
                      -

                      Compression

                      -

                      We support compression and decompression with gzip, Brotli, and Zstandard. Define the corresponding macro when you compile.

                      - - - - -
                      MethodMacro
                      gzipCPPHTTPLIB_ZLIB_SUPPORT
                      BrotliCPPHTTPLIB_BROTLI_SUPPORT
                      ZstandardCPPHTTPLIB_ZSTD_SUPPORT
                      -
                      -httplib::Client cli("https://example.com");
                      -cli.set_compress(true);    // Compress request body
                      -cli.set_decompress(true);  // Decompress response body
                      -
                      -
                      -httplib::Client cli("https://example.com");
                      -cli.set_compress(true);    // Compress request body
                      -cli.set_decompress(true);  // Decompress response body
                      -
                      -
                      -

                      Proxy

                      -

                      You can connect through an HTTP proxy.

                      -
                      -httplib::Client cli("https://example.com");
                      -cli.set_proxy("proxy.example.com", 8080);
                      -cli.set_proxy_basic_auth("user", "password");
                      -
                      -
                      -httplib::Client cli("https://example.com");
                      -cli.set_proxy("proxy.example.com", 8080);
                      -cli.set_proxy_basic_auth("user", "password");
                      -
                      -
                      -

                      Timeouts

                      -

                      You can set connection, read, and write timeouts individually.

                      -
                      -httplib::Client cli("https://example.com");
                      -cli.set_connection_timeout(5, 0);  // 5 seconds
                      -cli.set_read_timeout(10, 0);       // 10 seconds
                      -cli.set_write_timeout(10, 0);      // 10 seconds
                      -
                      -
                      -httplib::Client cli("https://example.com");
                      -cli.set_connection_timeout(5, 0);  // 5 seconds
                      -cli.set_read_timeout(10, 0);       // 10 seconds
                      -cli.set_write_timeout(10, 0);      // 10 seconds
                      -
                      -
                      -

                      Keep-Alive

                      -

                      If you're making multiple requests to the same server, enable Keep-Alive. It reuses the TCP connection, which is much more efficient.

                      -
                      -httplib::Client cli("https://example.com");
                      -cli.set_keep_alive(true);
                      -
                      -
                      -httplib::Client cli("https://example.com");
                      -cli.set_keep_alive(true);
                      -
                      -
                      -

                      Server Middleware

                      -

                      You can hook into request processing before and after handlers run.

                      -
                      -svr.set_pre_routing_handler([](const auto &req, auto &res) {
                      -    // Runs before every request
                      -    return httplib::Server::HandlerResponse::Unhandled;  // Continue to normal routing
                      -});
                      -
                      -svr.set_post_routing_handler([](const auto &req, auto &res) {
                      -    // Runs after the response is sent
                      -    res.set_header("X-Server", "cpp-httplib");
                      -});
                      -
                      -
                      -svr.set_pre_routing_handler([](const auto &req, auto &res) {
                      -    // Runs before every request
                      -    return httplib::Server::HandlerResponse::Unhandled;  // Continue to normal routing
                      -});
                      -
                      -svr.set_post_routing_handler([](const auto &req, auto &res) {
                      -    // Runs after the response is sent
                      -    res.set_header("X-Server", "cpp-httplib");
                      -});
                      -
                      -
                      -

                      Use req.user_data to pass data from middleware to handlers. This is useful for sharing things like decoded auth tokens.

                      -
                      -svr.set_pre_routing_handler([](const auto &req, auto &res) {
                      -    req.user_data["auth_user"] = std::string("alice");
                      -    return httplib::Server::HandlerResponse::Unhandled;
                      -});
                      -
                      -svr.Get("/me", [](const auto &req, auto &res) {
                      -    auto user = std::any_cast<std::string>(req.user_data.at("auth_user"));
                      -    res.set_content("Hello, " + user, "text/plain");
                      -});
                      -
                      -
                      -svr.set_pre_routing_handler([](const auto &req, auto &res) {
                      -    req.user_data["auth_user"] = std::string("alice");
                      -    return httplib::Server::HandlerResponse::Unhandled;
                      -});
                      -
                      -svr.Get("/me", [](const auto &req, auto &res) {
                      -    auto user = std::any_cast<std::string>(req.user_data.at("auth_user"));
                      -    res.set_content("Hello, " + user, "text/plain");
                      -});
                      -
                      -
                      -

                      You can also customize error and exception handlers.

                      -
                      -svr.set_error_handler([](const auto &req, auto &res) {
                      -    res.set_content("Custom Error Page", "text/html");
                      -});
                      -
                      -svr.set_exception_handler([](const auto &req, auto &res, std::exception_ptr ep) {
                      -    res.status = 500;
                      -    res.set_content("Internal Server Error", "text/plain");
                      -});
                      -
                      -
                      -svr.set_error_handler([](const auto &req, auto &res) {
                      -    res.set_content("Custom Error Page", "text/html");
                      -});
                      -
                      -svr.set_exception_handler([](const auto &req, auto &res, std::exception_ptr ep) {
                      -    res.status = 500;
                      -    res.set_content("Internal Server Error", "text/plain");
                      -});
                      -
                      -
                      -

                      Logging

                      -

                      You can set a logger on both the server and the client.

                      -
                      -svr.set_logger([](const auto &req, const auto &res) {
                      -    std::cout << req.method << " " << req.path << " " << res.status << std::endl;
                      -});
                      -
                      -
                      -svr.set_logger([](const auto &req, const auto &res) {
                      -    std::cout << req.method << " " << req.path << " " << res.status << std::endl;
                      -});
                      -
                      -
                      -

                      Unix Domain Socket

                      -

                      In addition to TCP, we support Unix Domain Sockets. You can use them for inter-process communication on the same machine.

                      -
                      -// Server
                      -httplib::Server svr;
                      -svr.set_address_family(AF_UNIX);
                      -svr.listen("/tmp/httplib.sock", 0);
                      -
                      -
                      -// Server
                      -httplib::Server svr;
                      -svr.set_address_family(AF_UNIX);
                      -svr.listen("/tmp/httplib.sock", 0);
                      -
                      -
                      -// Client
                      -httplib::Client cli("http://localhost");
                      -cli.set_address_family(AF_UNIX);
                      -cli.set_hostname_addr_map({{"localhost", "/tmp/httplib.sock"}});
                      -
                      -auto res = cli.Get("/");
                      -
                      -
                      -// Client
                      -httplib::Client cli("http://localhost");
                      -cli.set_address_family(AF_UNIX);
                      -cli.set_hostname_addr_map({{"localhost", "/tmp/httplib.sock"}});
                      -
                      -auto res = cli.Get("/");
                      -
                      -
                      -

                      Learn More

                      -

                      Want to dig deeper? Check out these resources.

                      -
                        -
                      • Cookbook — A collection of recipes for common use cases
                      • -
                      • README — Full API reference
                      • -
                      • README-sse — How to use Server-Sent Events
                      • -
                      • README-stream — How to use the Streaming API
                      • -
                      • README-websocket — How to use the WebSocket server
                      • -
                      - -
                      -
                      - -
                      - - - - -
                      -
                      -
                      - - - ESC -
                      -
                        -
                        -
                        - - - - diff --git a/docs/en/tour/index.html b/docs/en/tour/index.html deleted file mode 100644 index 46940e7..0000000 --- a/docs/en/tour/index.html +++ /dev/null @@ -1,143 +0,0 @@ - - - - - - A Tour of cpp-httplib - cpp-httplib - - - - - -
                        -
                        - cpp-httplib v0.36.0 -
                        - -
                        - - - -
                        - - -
                        - -
                        - -
                        -
                        - - - -
                        - - -
                        -
                        -

                        A Tour of cpp-httplib

                        -

                        This is a step-by-step tutorial that walks you through the basics of cpp-httplib. Each chapter builds on the previous one, so please read them in order starting from Chapter 1.

                        -
                          -
                        1. Getting Started — Get httplib.h and build a Hello World server
                        2. -
                        3. Basic Client — Send GET/POST requests and use path parameters
                        4. -
                        5. Basic Server — Routing, path parameters, and building responses
                        6. -
                        7. Static File Server — Serve static files
                        8. -
                        9. TLS Setup — Set up OpenSSL / mbedTLS
                        10. -
                        11. HTTPS Client — Make requests to HTTPS sites
                        12. -
                        13. HTTPS Server — Build an HTTPS server
                        14. -
                        15. WebSocket — Learn the basics of WebSocket communication
                        16. -
                        17. What's Next — Explore more features
                        18. -
                        - -
                        -
                        - -
                        - - - - -
                        -
                        -
                        - - - ESC -
                        -
                          -
                          -
                          - - - - diff --git a/docs/favicon.svg b/docs/favicon.svg deleted file mode 100644 index 9e824c2..0000000 --- a/docs/favicon.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index a6c85f3..0000000 --- a/docs/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -Redirecting... - - -

                          Redirecting to /cpp-httplib/en/...

                          - - \ No newline at end of file diff --git a/docs/ja/cookbook/index.html b/docs/ja/cookbook/index.html deleted file mode 100644 index 4171a36..0000000 --- a/docs/ja/cookbook/index.html +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - Cookbook - cpp-httplib - - - - - -
                          -
                          - cpp-httplib v0.36.0 -
                          - -
                          - - - -
                          - - -
                          - -
                          - -
                          -
                          - - - -
                          - - -
                          -
                          -

                          Cookbook

                          -

                          This section is under construction.

                          -

                          Check back soon for a collection of recipes organized by topic.

                          - -
                          -
                          - -
                          - - - - -
                          -
                          -
                          - - - ESC -
                          -
                            -
                            -
                            - - - - diff --git a/docs/ja/index.html b/docs/ja/index.html deleted file mode 100644 index 2fb9b12..0000000 --- a/docs/ja/index.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - cpp-httplib - cpp-httplib - - - - - -
                            -
                            - cpp-httplib v0.36.0 -
                            - -
                            - - - -
                            - - -
                            - -
                            - -
                            -
                            - - - -
                            - -
                            -
                            -

                            cpp-httplib

                            -

                            cpp-httplibは、C++用のHTTP/HTTPSライブラリです。httplib.h というヘッダーファイルを1枚コピーするだけで使えます。

                            -

                            C++でちょっとしたHTTPサーバーやクライアントが必要になったとき、すぐに動くものが欲しいですよね。cpp-httplibはまさにそのために作られました。サーバーもクライアントも、数行のコードで書き始められます。

                            -

                            APIはラムダ式をベースにした直感的な設計で、C++11以降のコンパイラーがあればどこでも動きます。Windows、macOS、Linux — お使いの環境をそのまま使えます。

                            -

                            HTTPSも使えます。OpenSSLやmbedTLSをリンクするだけで、サーバー・クライアントの両方がTLSに対応します。Content-Encoding(gzip, brotli等)、ファイルアップロードなど、実際の開発で必要になる機能もひと通り揃っています。WebSocketもサポートしています。

                            -

                            内部的にはブロッキングI/Oとスレッドプールを使っています。大量の同時接続を捌くような用途には向きませんが、APIサーバーやツールの組み込みHTTP、テスト用のモックサーバーなど、多くのユースケースで十分な性能を発揮します。

                            -

                            「今日の課題を、今日中に解決する」— cpp-httplibが目指しているのは、そういうシンプルさです。

                            -

                            ドキュメント

                            -
                              -
                            • A Tour of cpp-httplib — 基本を順を追って学べるチュートリアル。初めての方はここから
                            • -
                            • Cookbook — 目的別のレシピ集。必要なトピックから読めます
                            • -
                            - -
                            -
                            - -
                            - - - - -
                            -
                            -
                            - - - ESC -
                            -
                              -
                              -
                              - - - - diff --git a/docs/ja/tour/01-getting-started/index.html b/docs/ja/tour/01-getting-started/index.html deleted file mode 100644 index 1f05ac0..0000000 --- a/docs/ja/tour/01-getting-started/index.html +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - Getting Started - cpp-httplib - - - - - -
                              -
                              - cpp-httplib v0.36.0 -
                              - -
                              - - - -
                              - - -
                              - -
                              - -
                              -
                              - - - -
                              - - -
                              -
                              -

                              Getting Started

                              -

                              cpp-httplibを始めるのに必要なのは、httplib.hとC++コンパイラーだけです。ファイルをダウンロードして、Hello Worldサーバーを動かすところまでやってみましょう。

                              -

                              httplib.h の入手

                              -

                              GitHubから直接ダウンロードできます。常に最新版を使ってください。

                              -
                              -curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
                              -
                              -
                              -curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
                              -
                              -
                              -

                              ダウンロードした httplib.h をプロジェクトのディレクトリに置けば、準備完了です。

                              -

                              コンパイラーの準備

                              - - - - -
                              OS開発環境セットアップ
                              macOSApple ClangXcode Command Line Tools (xcode-select --install)
                              Ubuntuclang++ または g++apt install clang または apt install g++
                              WindowsMSVCVisual 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);
                              -}
                              -
                              -
                              -#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
                              -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
                              -
                              -
                              -# macOS / Linux
                              -./server
                              -
                              -# Windows
                              -server.exe
                              -
                              -
                              -

                              ブラウザで http://localhost:8080 を開いてください。"Hello, World!" と表示されれば成功です。

                              -

                              curl でも確認できます。

                              -
                              -curl http://localhost:8080/
                              -# Hello, World!
                              -
                              -
                              -curl http://localhost:8080/
                              -# Hello, World!
                              -
                              -
                              -

                              サーバーを停止するには、ターミナルで Ctrl+C を押します。

                              -

                              次のステップ

                              -

                              サーバーの基本がわかりましたね。次は、クライアント側を見てみましょう。cpp-httplibはHTTPクライアント機能も備えています。

                              -

                              次: Basic Client

                              - -
                              -
                              - -
                              - - - - -
                              -
                              -
                              - - - ESC -
                              -
                                -
                                -
                                - - - - diff --git a/docs/ja/tour/02-basic-client/index.html b/docs/ja/tour/02-basic-client/index.html deleted file mode 100644 index 08f94de..0000000 --- a/docs/ja/tour/02-basic-client/index.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - Basic Client - cpp-httplib - - - - - -
                                -
                                - cpp-httplib v0.36.0 -
                                - -
                                - - - -
                                - - -
                                - -
                                - -
                                -
                                - - - -
                                - - -
                                -
                                -

                                Basic Client

                                -

                                cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。httplib::Client を使って、GETやPOSTリクエストを送ってみましょう。

                                -

                                テスト用サーバーの準備

                                -

                                クライアントの動作を確認するために、リクエストを受け付けるサーバーを用意します。次のコードを保存し、前章と同じ手順でコンパイル・実行してください。サーバーの詳しい解説は次章で行います。

                                -
                                -#include "httplib.h"
                                -#include <iostream>
                                -
                                -int main() {
                                -    httplib::Server svr;
                                -
                                -    svr.Get("/hi", [](const auto &, auto &res) {
                                -        res.set_content("Hello!", "text/plain");
                                -    });
                                -
                                -    svr.Get("/search", [](const auto &req, auto &res) {
                                -        auto q = req.get_param_value("q");
                                -        res.set_content("Query: " + q, "text/plain");
                                -    });
                                -
                                -    svr.Post("/post", [](const auto &req, auto &res) {
                                -        res.set_content(req.body, "text/plain");
                                -    });
                                -
                                -    svr.Post("/submit", [](const auto &req, auto &res) {
                                -        std::string result;
                                -        for (auto &[key, val] : req.params) {
                                -            result += key + " = " + val + "\n";
                                -        }
                                -        res.set_content(result, "text/plain");
                                -    });
                                -
                                -    svr.Post("/upload", [](const auto &req, auto &res) {
                                -        auto f = req.form.get_file("file");
                                -        auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
                                -        res.set_content(content, "text/plain");
                                -    });
                                -
                                -    svr.Get("/users/:id", [](const auto &req, auto &res) {
                                -        auto id = req.path_params.at("id");
                                -        res.set_content("User ID: " + id, "text/plain");
                                -    });
                                -
                                -    svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
                                -        auto id = req.matches[1];
                                -        res.set_content("File ID: " + std::string(id), "text/plain");
                                -    });
                                -
                                -    std::cout << "Listening on port 8080..." << std::endl;
                                -    svr.listen("0.0.0.0", 8080);
                                -}
                                -
                                -
                                -#include "httplib.h"
                                -#include <iostream>
                                -
                                -int main() {
                                -    httplib::Server svr;
                                -
                                -    svr.Get("/hi", [](const auto &, auto &res) {
                                -        res.set_content("Hello!", "text/plain");
                                -    });
                                -
                                -    svr.Get("/search", [](const auto &req, auto &res) {
                                -        auto q = req.get_param_value("q");
                                -        res.set_content("Query: " + q, "text/plain");
                                -    });
                                -
                                -    svr.Post("/post", [](const auto &req, auto &res) {
                                -        res.set_content(req.body, "text/plain");
                                -    });
                                -
                                -    svr.Post("/submit", [](const auto &req, auto &res) {
                                -        std::string result;
                                -        for (auto &[key, val] : req.params) {
                                -            result += key + " = " + val + "\n";
                                -        }
                                -        res.set_content(result, "text/plain");
                                -    });
                                -
                                -    svr.Post("/upload", [](const auto &req, auto &res) {
                                -        auto f = req.form.get_file("file");
                                -        auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
                                -        res.set_content(content, "text/plain");
                                -    });
                                -
                                -    svr.Get("/users/:id", [](const auto &req, auto &res) {
                                -        auto id = req.path_params.at("id");
                                -        res.set_content("User ID: " + id, "text/plain");
                                -    });
                                -
                                -    svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
                                -        auto id = req.matches[1];
                                -        res.set_content("File ID: " + std::string(id), "text/plain");
                                -    });
                                -
                                -    std::cout << "Listening on port 8080..." << std::endl;
                                -    svr.listen("0.0.0.0", 8080);
                                -}
                                -
                                -
                                -

                                GETリクエスト

                                -

                                サーバーが起動したら、別のターミナルを開いて試してみましょう。まず、最もシンプルなGETリクエストです。

                                -
                                -#include "httplib.h"
                                -#include <iostream>
                                -
                                -int main() {
                                -    httplib::Client cli("http://localhost:8080");
                                -
                                -    auto res = cli.Get("/hi");
                                -    if (res) {
                                -        std::cout << res->status << std::endl;  // 200
                                -        std::cout << res->body << std::endl;    // Hello!
                                -    }
                                -}
                                -
                                -
                                -#include "httplib.h"
                                -#include <iostream>
                                -
                                -int main() {
                                -    httplib::Client cli("http://localhost:8080");
                                -
                                -    auto res = cli.Get("/hi");
                                -    if (res) {
                                -        std::cout << res->status << std::endl;  // 200
                                -        std::cout << res->body << std::endl;    // Hello!
                                -    }
                                -}
                                -
                                -
                                -

                                httplib::Client のコンストラクターにサーバーのアドレスを渡し、Get() でリクエストを送ります。戻り値の res からステータスコードやボディを取得できます。

                                -

                                対応する curl コマンドはこうなります。

                                -
                                -curl http://localhost:8080/hi
                                -# Hello!
                                -
                                -
                                -curl http://localhost:8080/hi
                                -# Hello!
                                -
                                -
                                -

                                レスポンスの確認

                                -

                                レスポンスには、ステータスコードとボディ以外にもヘッダー情報が含まれています。

                                -
                                -auto res = cli.Get("/hi");
                                -if (res) {
                                -    // ステータスコード
                                -    std::cout << res->status << std::endl;  // 200
                                -
                                -    // ボディ
                                -    std::cout << res->body << std::endl;  // Hello!
                                -
                                -    // ヘッダー
                                -    std::cout << res->get_header_value("Content-Type") << std::endl;  // text/plain
                                -}
                                -
                                -
                                -auto res = cli.Get("/hi");
                                -if (res) {
                                -    // ステータスコード
                                -    std::cout << res->status << std::endl;  // 200
                                -
                                -    // ボディ
                                -    std::cout << res->body << std::endl;  // Hello!
                                -
                                -    // ヘッダー
                                -    std::cout << res->get_header_value("Content-Type") << std::endl;  // text/plain
                                -}
                                -
                                -
                                -

                                res->bodystd::string なので、JSON レスポンスをパースしたい場合は nlohmann/json などの JSON ライブラリにそのまま渡せます。

                                -

                                クエリパラメーター

                                -

                                GETリクエストにクエリパラメーターを付けるには、URLに直接書くか、httplib::Params を使います。

                                -
                                -auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
                                -if (res) {
                                -    std::cout << res->body << std::endl;  // Query: cpp-httplib
                                -}
                                -
                                -
                                -auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
                                -if (res) {
                                -    std::cout << res->body << std::endl;  // Query: cpp-httplib
                                -}
                                -
                                -
                                -

                                httplib::Params を使うと、特殊文字のURLエンコードを自動で行ってくれます。

                                -
                                -curl "http://localhost:8080/search?q=cpp-httplib"
                                -# Query: cpp-httplib
                                -
                                -
                                -curl "http://localhost:8080/search?q=cpp-httplib"
                                -# Query: cpp-httplib
                                -
                                -
                                -

                                パスパラメーター

                                -

                                URLのパスに値を直接埋め込む場合も、クライアント側は特別なAPIは不要です。パスをそのまま Get() に渡すだけです。

                                -
                                -auto res = cli.Get("/users/42");
                                -if (res) {
                                -    std::cout << res->body << std::endl;  // User ID: 42
                                -}
                                -
                                -
                                -auto res = cli.Get("/users/42");
                                -if (res) {
                                -    std::cout << res->body << std::endl;  // User ID: 42
                                -}
                                -
                                -
                                -curl http://localhost:8080/users/42
                                -# User ID: 42
                                -
                                -
                                -curl http://localhost:8080/users/42
                                -# User ID: 42
                                -
                                -
                                -

                                テスト用サーバーには、正規表現でIDを数字のみに絞った /files/(\d+) もあります。

                                -
                                -auto res = cli.Get("/files/42");
                                -if (res) {
                                -    std::cout << res->body << std::endl;  // File ID: 42
                                -}
                                -
                                -
                                -auto res = cli.Get("/files/42");
                                -if (res) {
                                -    std::cout << res->body << std::endl;  // File ID: 42
                                -}
                                -
                                -
                                -curl http://localhost:8080/files/42
                                -# File ID: 42
                                -
                                -
                                -curl http://localhost:8080/files/42
                                -# File ID: 42
                                -
                                -
                                -

                                /files/abc のように数字以外を渡すと404が返ります。仕組みは次章で解説します。

                                -

                                リクエストヘッダー

                                -

                                カスタムHTTPヘッダーを付けるには、httplib::Headers を渡します。Get()Post() のどちらでも使えます。

                                -
                                -auto res = cli.Get("/hi", httplib::Headers{
                                -    {"Authorization", "Bearer my-token"}
                                -});
                                -
                                -
                                -auto res = cli.Get("/hi", httplib::Headers{
                                -    {"Authorization", "Bearer my-token"}
                                -});
                                -
                                -
                                -curl -H "Authorization: Bearer my-token" http://localhost:8080/hi
                                -
                                -
                                -curl -H "Authorization: Bearer my-token" http://localhost:8080/hi
                                -
                                -
                                -

                                POSTリクエスト

                                -

                                テキストデータをPOSTしてみましょう。Post() の第2引数にボディ、第3引数にContent-Typeを指定します。

                                -
                                -auto res = cli.Post("/post", "Hello, Server!", "text/plain");
                                -if (res) {
                                -    std::cout << res->status << std::endl;  // 200
                                -    std::cout << res->body << std::endl;    // Hello, Server!
                                -}
                                -
                                -
                                -auto res = cli.Post("/post", "Hello, Server!", "text/plain");
                                -if (res) {
                                -    std::cout << res->status << std::endl;  // 200
                                -    std::cout << res->body << std::endl;    // Hello, Server!
                                -}
                                -
                                -
                                -

                                テスト用サーバーの /post はボディをそのまま返すので、送った文字列がそのまま返ってきます。

                                -
                                -curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post
                                -# Hello, Server!
                                -
                                -
                                -curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post
                                -# Hello, Server!
                                -
                                -
                                -

                                フォームデータの送信

                                -

                                HTMLフォームのように、キーと値のペアを送ることもできます。httplib::Params を使います。

                                -
                                -auto res = cli.Post("/submit", httplib::Params{
                                -    {"name", "Alice"},
                                -    {"age", "30"}
                                -});
                                -if (res) {
                                -    std::cout << res->body << std::endl;
                                -    // age = 30
                                -    // name = Alice
                                -}
                                -
                                -
                                -auto res = cli.Post("/submit", httplib::Params{
                                -    {"name", "Alice"},
                                -    {"age", "30"}
                                -});
                                -if (res) {
                                -    std::cout << res->body << std::endl;
                                -    // age = 30
                                -    // name = Alice
                                -}
                                -
                                -
                                -

                                これは application/x-www-form-urlencoded 形式で送信されます。

                                -
                                -curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
                                -
                                -
                                -curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
                                -
                                -
                                -

                                ファイルのPOST

                                -

                                ファイルをアップロードするには、httplib::UploadFormDataItems を使ってマルチパートフォームデータとして送信します。

                                -
                                -auto res = cli.Post("/upload", httplib::UploadFormDataItems{
                                -    {"file", "Hello, File!", "hello.txt", "text/plain"}
                                -});
                                -if (res) {
                                -    std::cout << res->body << std::endl;  // hello.txt (12 bytes)
                                -}
                                -
                                -
                                -auto res = cli.Post("/upload", httplib::UploadFormDataItems{
                                -    {"file", "Hello, File!", "hello.txt", "text/plain"}
                                -});
                                -if (res) {
                                -    std::cout << res->body << std::endl;  // hello.txt (12 bytes)
                                -}
                                -
                                -
                                -

                                UploadFormDataItems の各要素は {name, content, filename, content_type} の4つのフィールドで構成されます。

                                -
                                -curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload
                                -
                                -
                                -curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload
                                -
                                -
                                -

                                エラーハンドリング

                                -

                                ネットワーク通信では、サーバーに接続できない場合があります。res が有効かどうかを必ず確認しましょう。

                                -
                                -httplib::Client cli("http://localhost:9999");  // 存在しないポート
                                -auto res = cli.Get("/hi");
                                -
                                -if (!res) {
                                -    // 接続エラー
                                -    std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
                                -    // Error: Connection
                                -    return 1;
                                -}
                                -
                                -// ここに到達すればレスポンスを受信できている
                                -if (res->status != 200) {
                                -    std::cout << "HTTP Error: " << res->status << std::endl;
                                -    return 1;
                                -}
                                -
                                -std::cout << res->body << std::endl;
                                -
                                -
                                -httplib::Client cli("http://localhost:9999");  // 存在しないポート
                                -auto res = cli.Get("/hi");
                                -
                                -if (!res) {
                                -    // 接続エラー
                                -    std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
                                -    // Error: Connection
                                -    return 1;
                                -}
                                -
                                -// ここに到達すればレスポンスを受信できている
                                -if (res->status != 200) {
                                -    std::cout << "HTTP Error: " << res->status << std::endl;
                                -    return 1;
                                -}
                                -
                                -std::cout << res->body << std::endl;
                                -
                                -
                                -

                                エラーには2つのレベルがあります。

                                -
                                  -
                                • 接続エラー: サーバーに到達できなかった場合。res が偽になり、res.error() でエラーの種類を取得できます
                                • -
                                • HTTPエラー: サーバーからエラーステータス(404、500など)が返ってきた場合。res は真ですが、res->status を確認する必要があります
                                • -
                                -

                                次のステップ

                                -

                                クライアントからリクエストを送る方法がわかりました。次は、サーバー側をもっと詳しく見てみましょう。ルーティングやパスパラメータなど、サーバーの機能を掘り下げます。

                                -

                                次: Basic Server

                                - -
                                -
                                - -
                                - - - - -
                                -
                                -
                                - - - ESC -
                                -
                                  -
                                  -
                                  - - - - diff --git a/docs/ja/tour/03-basic-server/index.html b/docs/ja/tour/03-basic-server/index.html deleted file mode 100644 index 6502aee..0000000 --- a/docs/ja/tour/03-basic-server/index.html +++ /dev/null @@ -1,484 +0,0 @@ - - - - - - Basic Server - cpp-httplib - - - - - -
                                  -
                                  - cpp-httplib v0.36.0 -
                                  - -
                                  - - - -
                                  - - -
                                  - -
                                  - -
                                  -
                                  - - - -
                                  - - -
                                  -
                                  -

                                  Basic Server

                                  -

                                  前章ではクライアントからリクエストを送りました。そのとき、テスト用サーバーを用意しましたね。この章では、あのサーバーの仕組みをひとつずつ紐解いていきます。

                                  -

                                  サーバーの起動

                                  -

                                  ルーティングを登録したら、最後に svr.listen() を呼んでサーバーを起動します。

                                  -
                                  -svr.listen("0.0.0.0", 8080);
                                  -
                                  -
                                  -svr.listen("0.0.0.0", 8080);
                                  -
                                  -
                                  -

                                  第1引数はホスト、第2引数はポート番号です。"0.0.0.0" を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは "127.0.0.1" を使います。

                                  -

                                  listen() はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで Ctrl+C を押すか、別スレッドから svr.stop() を呼ぶまでサーバーは動き続けます。

                                  -

                                  ルーティング

                                  -

                                  サーバーの核になるのは「ルーティング」です。どのURLに、どのHTTPメソッドでアクセスされたら、何をするか。それを登録する仕組みです。

                                  -
                                  -httplib::Server svr;
                                  -
                                  -svr.Get("/hi", [](const httplib::Request &req, httplib::Response &res) {
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -httplib::Server svr;
                                  -
                                  -svr.Get("/hi", [](const httplib::Request &req, httplib::Response &res) {
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  svr.Get() は、GETリクエストに対するハンドラーを登録します。第1引数がパス、第2引数がハンドラー関数です。/hi にGETリクエストが来たら、このラムダが呼ばれます。

                                  -

                                  HTTPメソッドごとにメソッドが用意されています。

                                  -
                                  -svr.Get("/path",    handler);  // GET
                                  -svr.Post("/path",   handler);  // POST
                                  -svr.Put("/path",    handler);  // PUT
                                  -svr.Delete("/path", handler);  // DELETE
                                  -
                                  -
                                  -svr.Get("/path",    handler);  // GET
                                  -svr.Post("/path",   handler);  // POST
                                  -svr.Put("/path",    handler);  // PUT
                                  -svr.Delete("/path", handler);  // DELETE
                                  -
                                  -
                                  -

                                  ハンドラーのシグネチャは (const httplib::Request &req, httplib::Response &res) です。auto を使って短く書くこともできます。

                                  -
                                  -svr.Get("/hi", [](const auto &req, auto &res) {
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/hi", [](const auto &req, auto &res) {
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  パスが一致したときだけハンドラーが呼ばれます。登録されていないパスにアクセスすると、自動的に404が返ります。

                                  -

                                  リクエストオブジェクト

                                  -

                                  ハンドラーの第1引数 req から、クライアントが送ってきた情報を読み取れます。

                                  -

                                  ボディ

                                  -

                                  req.body でリクエストボディを取得できます。型は std::string です。

                                  -
                                  -svr.Post("/post", [](const auto &req, auto &res) {
                                  -    // クライアントが送ったボディをそのまま返す
                                  -    res.set_content(req.body, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Post("/post", [](const auto &req, auto &res) {
                                  -    // クライアントが送ったボディをそのまま返す
                                  -    res.set_content(req.body, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  ヘッダー

                                  -

                                  req.get_header_value() でリクエストヘッダーの値を取得できます。

                                  -
                                  -svr.Get("/check", [](const auto &req, auto &res) {
                                  -    auto auth = req.get_header_value("Authorization");
                                  -    res.set_content("Auth: " + auth, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/check", [](const auto &req, auto &res) {
                                  -    auto auth = req.get_header_value("Authorization");
                                  -    res.set_content("Auth: " + auth, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  クエリパラメーターとフォームデータ

                                  -

                                  req.get_param_value() でパラメーターを取得できます。GETのクエリパラメーターと、POSTのフォームデータの両方に使えます。

                                  -
                                  -svr.Get("/search", [](const auto &req, auto &res) {
                                  -    auto q = req.get_param_value("q");
                                  -    res.set_content("Query: " + q, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/search", [](const auto &req, auto &res) {
                                  -    auto q = req.get_param_value("q");
                                  -    res.set_content("Query: " + q, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  /search?q=cpp-httplib にアクセスすると、q の値は "cpp-httplib" になります。

                                  -

                                  すべてのパラメーターをループで処理したいときは、req.params を使います。

                                  -
                                  -svr.Post("/submit", [](const auto &req, auto &res) {
                                  -    std::string result;
                                  -    for (auto &[key, val] : req.params) {
                                  -        result += key + " = " + val + "\n";
                                  -    }
                                  -    res.set_content(result, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Post("/submit", [](const auto &req, auto &res) {
                                  -    std::string result;
                                  -    for (auto &[key, val] : req.params) {
                                  -        result += key + " = " + val + "\n";
                                  -    }
                                  -    res.set_content(result, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  ファイルアップロード

                                  -

                                  マルチパートフォームでアップロードされたファイルは、req.form.get_file() で取得します。

                                  -
                                  -svr.Post("/upload", [](const auto &req, auto &res) {
                                  -    auto f = req.form.get_file("file");
                                  -    auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
                                  -    res.set_content(content, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Post("/upload", [](const auto &req, auto &res) {
                                  -    auto f = req.form.get_file("file");
                                  -    auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
                                  -    res.set_content(content, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  f.filename でファイル名、f.content でファイルの中身にアクセスできます。

                                  -

                                  パスパラメーター

                                  -

                                  URLの一部を変数として受け取りたいことがあります。たとえば /users/4242 を取得したい場合です。:param 記法を使うと、URLの一部をキャプチャできます。

                                  -
                                  -svr.Get("/users/:id", [](const auto &req, auto &res) {
                                  -    auto id = req.path_params.at("id");
                                  -    res.set_content("User ID: " + id, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/users/:id", [](const auto &req, auto &res) {
                                  -    auto id = req.path_params.at("id");
                                  -    res.set_content("User ID: " + id, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  /users/42 にアクセスすると、req.path_params.at("id")"42" を返します。/users/100 なら "100" です。

                                  -

                                  複数のパスパラメーターも使えます。

                                  -
                                  -svr.Get("/users/:user_id/posts/:post_id", [](const auto &req, auto &res) {
                                  -    auto user_id = req.path_params.at("user_id");
                                  -    auto post_id = req.path_params.at("post_id");
                                  -    res.set_content("User: " + user_id + ", Post: " + post_id, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/users/:user_id/posts/:post_id", [](const auto &req, auto &res) {
                                  -    auto user_id = req.path_params.at("user_id");
                                  -    auto post_id = req.path_params.at("post_id");
                                  -    res.set_content("User: " + user_id + ", Post: " + post_id, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  正規表現パターン

                                  -

                                  :param の代わりに正規表現をパスに書くこともできます。キャプチャグループの値は req.matches で取得します。型は std::smatch です。

                                  -
                                  -// 数字のみのIDを受け付ける
                                  -svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
                                  -    auto id = req.matches[1];  // 最初のキャプチャグループ
                                  -    res.set_content("File ID: " + std::string(id), "text/plain");
                                  -});
                                  -
                                  -
                                  -// 数字のみのIDを受け付ける
                                  -svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
                                  -    auto id = req.matches[1];  // 最初のキャプチャグループ
                                  -    res.set_content("File ID: " + std::string(id), "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  /files/42 にはマッチしますが、/files/abc にはマッチしません。入力値を絞り込みたいときに便利です。

                                  -

                                  レスポンスの組み立て

                                  -

                                  ハンドラーの第2引数 res を使って、クライアントに返すレスポンスを組み立てます。

                                  -

                                  ボディとContent-Type

                                  -

                                  res.set_content() でボディとContent-Typeを設定します。これだけでステータスコード200のレスポンスが返ります。

                                  -
                                  -svr.Get("/hi", [](const auto &req, auto &res) {
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/hi", [](const auto &req, auto &res) {
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  ステータスコード

                                  -

                                  ステータスコードを変えたいときは、res.status に代入します。

                                  -
                                  -svr.Get("/not-found", [](const auto &req, auto &res) {
                                  -    res.status = 404;
                                  -    res.set_content("Not found", "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/not-found", [](const auto &req, auto &res) {
                                  -    res.status = 404;
                                  -    res.set_content("Not found", "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  レスポンスヘッダー

                                  -

                                  res.set_header() でレスポンスヘッダーを追加できます。

                                  -
                                  -svr.Get("/with-header", [](const auto &req, auto &res) {
                                  -    res.set_header("X-Custom", "my-value");
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/with-header", [](const auto &req, auto &res) {
                                  -    res.set_header("X-Custom", "my-value");
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  前章のサーバーを読み解く

                                  -

                                  ここまでの知識を使って、前章で用意したテスト用サーバーを改めて見てみましょう。

                                  -

                                  GET /hi

                                  -
                                  -svr.Get("/hi", [](const auto &, auto &res) {
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/hi", [](const auto &, auto &res) {
                                  -    res.set_content("Hello!", "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  最もシンプルなハンドラーです。リクエストの情報は使わないので、req の変数名を省略しています。"Hello!" というテキストをそのまま返します。

                                  -

                                  GET /search

                                  -
                                  -svr.Get("/search", [](const auto &req, auto &res) {
                                  -    auto q = req.get_param_value("q");
                                  -    res.set_content("Query: " + q, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/search", [](const auto &req, auto &res) {
                                  -    auto q = req.get_param_value("q");
                                  -    res.set_content("Query: " + q, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  req.get_param_value("q") でクエリパラメーター q の値を取り出します。/search?q=cpp-httplib なら、レスポンスは "Query: cpp-httplib" になります。

                                  -

                                  POST /post

                                  -
                                  -svr.Post("/post", [](const auto &req, auto &res) {
                                  -    res.set_content(req.body, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Post("/post", [](const auto &req, auto &res) {
                                  -    res.set_content(req.body, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  クライアントが送ったリクエストボディを、そのままレスポンスとして返すエコーサーバーです。req.body にボディが丸ごと入っています。

                                  -

                                  POST /submit

                                  -
                                  -svr.Post("/submit", [](const auto &req, auto &res) {
                                  -    std::string result;
                                  -    for (auto &[key, val] : req.params) {
                                  -        result += key + " = " + val + "\n";
                                  -    }
                                  -    res.set_content(result, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Post("/submit", [](const auto &req, auto &res) {
                                  -    std::string result;
                                  -    for (auto &[key, val] : req.params) {
                                  -        result += key + " = " + val + "\n";
                                  -    }
                                  -    res.set_content(result, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  フォームデータとして送られたキーと値のペアを、req.params でループ処理しています。構造化束縛 auto &[key, val] を使って、各ペアを取り出しています。

                                  -

                                  POST /upload

                                  -
                                  -svr.Post("/upload", [](const auto &req, auto &res) {
                                  -    auto f = req.form.get_file("file");
                                  -    auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
                                  -    res.set_content(content, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Post("/upload", [](const auto &req, auto &res) {
                                  -    auto f = req.form.get_file("file");
                                  -    auto content = f.filename + " (" + std::to_string(f.content.size()) + " bytes)";
                                  -    res.set_content(content, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  マルチパートフォームで送られたファイルを受け取ります。req.form.get_file("file")"file" という名前のフィールドを取得し、f.filenamef.content.size() でファイル名とサイズを返しています。

                                  -

                                  GET /users/:id

                                  -
                                  -svr.Get("/users/:id", [](const auto &req, auto &res) {
                                  -    auto id = req.path_params.at("id");
                                  -    res.set_content("User ID: " + id, "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get("/users/:id", [](const auto &req, auto &res) {
                                  -    auto id = req.path_params.at("id");
                                  -    res.set_content("User ID: " + id, "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  :id の部分がパスパラメーターです。req.path_params.at("id") で値を取り出しています。/users/42 なら "42"/users/alice なら "alice" が得られます。

                                  -

                                  GET /files/(\d+)

                                  -
                                  -svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
                                  -    auto id = req.matches[1];
                                  -    res.set_content("File ID: " + std::string(id), "text/plain");
                                  -});
                                  -
                                  -
                                  -svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
                                  -    auto id = req.matches[1];
                                  -    res.set_content("File ID: " + std::string(id), "text/plain");
                                  -});
                                  -
                                  -
                                  -

                                  正規表現 (\d+) で数字だけのIDにマッチします。/files/42 にはマッチしますが、/files/abc は404になります。req.matches[1] で最初のキャプチャグループの値を取得しています。

                                  -

                                  次のステップ

                                  -

                                  サーバーの基本がわかりましたね。ルーティング、リクエストの読み取り、レスポンスの組み立て。これだけで、十分に実用的なAPIサーバーが作れます。

                                  -

                                  次は、静的ファイルの配信を見てみましょう。HTMLやCSSを配信するサーバーを作ります。

                                  -

                                  次: Static File Server

                                  - -
                                  -
                                  - -
                                  - - - - -
                                  -
                                  -
                                  - - - ESC -
                                  -
                                    -
                                    -
                                    - - - - diff --git a/docs/ja/tour/04-static-file-server/index.html b/docs/ja/tour/04-static-file-server/index.html deleted file mode 100644 index 4487952..0000000 --- a/docs/ja/tour/04-static-file-server/index.html +++ /dev/null @@ -1,307 +0,0 @@ - - - - - - Static File Server - cpp-httplib - - - - - -
                                    -
                                    - cpp-httplib v0.36.0 -
                                    - -
                                    - - - -
                                    - - -
                                    - -
                                    - -
                                    -
                                    - - - -
                                    - - -
                                    -
                                    -

                                    Static File Server

                                    -

                                    cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。set_mount_point() を1行呼ぶだけです。

                                    -

                                    set_mount_point の基本

                                    -

                                    さっそくやってみましょう。set_mount_point() は、URLのパスとローカルディレクトリを紐づけます。

                                    -
                                    -#include "httplib.h"
                                    -#include <iostream>
                                    -
                                    -int main() {
                                    -    httplib::Server svr;
                                    -
                                    -    svr.set_mount_point("/", "./html");
                                    -
                                    -    std::cout << "Listening on port 8080..." << std::endl;
                                    -    svr.listen("0.0.0.0", 8080);
                                    -}
                                    -
                                    -
                                    -#include "httplib.h"
                                    -#include <iostream>
                                    -
                                    -int main() {
                                    -    httplib::Server svr;
                                    -
                                    -    svr.set_mount_point("/", "./html");
                                    -
                                    -    std::cout << "Listening on port 8080..." << std::endl;
                                    -    svr.listen("0.0.0.0", 8080);
                                    -}
                                    -
                                    -
                                    -

                                    第1引数がURLのマウントポイント、第2引数がローカルのディレクトリパスです。この例だと、/ へのリクエストを ./html ディレクトリから配信します。

                                    -

                                    試してみましょう。まず html ディレクトリを作って、index.html を置きます。

                                    -
                                    -mkdir html
                                    -
                                    -
                                    -mkdir html
                                    -
                                    -
                                    -<!DOCTYPE html>
                                    -<html>
                                    -<head><title>My Page</title></head>
                                    -<body>
                                    -    <h1>Hello from cpp-httplib!</h1>
                                    -    <p>This is a static file.</p>
                                    -</body>
                                    -</html>
                                    -
                                    -
                                    -<!DOCTYPE html>
                                    -<html>
                                    -<head><title>My Page</title></head>
                                    -<body>
                                    -    <h1>Hello from cpp-httplib!</h1>
                                    -    <p>This is a static file.</p>
                                    -</body>
                                    -</html>
                                    -
                                    -
                                    -

                                    コンパイルして起動します。

                                    -
                                    -g++ -std=c++17 -o server server.cpp -pthread
                                    -./server
                                    -
                                    -
                                    -g++ -std=c++17 -o server server.cpp -pthread
                                    -./server
                                    -
                                    -
                                    -

                                    ブラウザで http://localhost:8080 を開いてみてください。html/index.html の内容が表示されるはずです。http://localhost:8080/index.html でも同じページが返ります。

                                    -

                                    もちろん、前章のクライアントコードや curl でもアクセスできますよ。

                                    -
                                    -httplib::Client cli("http://localhost:8080");
                                    -auto res = cli.Get("/");
                                    -if (res) {
                                    -    std::cout << res->body << std::endl;  // HTMLが表示される
                                    -}
                                    -
                                    -
                                    -httplib::Client cli("http://localhost:8080");
                                    -auto res = cli.Get("/");
                                    -if (res) {
                                    -    std::cout << res->body << std::endl;  // HTMLが表示される
                                    -}
                                    -
                                    -
                                    -curl http://localhost:8080
                                    -
                                    -
                                    -curl http://localhost:8080
                                    -
                                    -
                                    -

                                    複数のマウントポイント

                                    -

                                    set_mount_point() は何回でも呼べます。URLのパスごとに、別々のディレクトリを割り当てられます。

                                    -
                                    -svr.set_mount_point("/", "./public");
                                    -svr.set_mount_point("/assets", "./static/assets");
                                    -svr.set_mount_point("/docs", "./documentation");
                                    -
                                    -
                                    -svr.set_mount_point("/", "./public");
                                    -svr.set_mount_point("/assets", "./static/assets");
                                    -svr.set_mount_point("/docs", "./documentation");
                                    -
                                    -
                                    -

                                    /assets/style.css なら ./static/assets/style.css を、/docs/guide.html なら ./documentation/guide.html を配信します。

                                    -

                                    ハンドラーとの組み合わせ

                                    -

                                    静的ファイルの配信と、前章で学んだルーティングハンドラーは共存できます。

                                    -
                                    -httplib::Server svr;
                                    -
                                    -// APIエンドポイント
                                    -svr.Get("/api/hello", [](const auto &, auto &res) {
                                    -    res.set_content(R"({"message":"Hello!"})", "application/json");
                                    -});
                                    -
                                    -// 静的ファイル配信
                                    -svr.set_mount_point("/", "./public");
                                    -
                                    -svr.listen("0.0.0.0", 8080);
                                    -
                                    -
                                    -httplib::Server svr;
                                    -
                                    -// APIエンドポイント
                                    -svr.Get("/api/hello", [](const auto &, auto &res) {
                                    -    res.set_content(R"({"message":"Hello!"})", "application/json");
                                    -});
                                    -
                                    -// 静的ファイル配信
                                    -svr.set_mount_point("/", "./public");
                                    -
                                    -svr.listen("0.0.0.0", 8080);
                                    -
                                    -
                                    -

                                    ハンドラーが先に評価されます。/api/hello にはハンドラーが応答し、それ以外のパスは ./public ディレクトリからファイルを探します。

                                    -

                                    レスポンスヘッダーの追加

                                    -

                                    set_mount_point() の第3引数にヘッダーを渡すと、静的ファイルのレスポンスにカスタムヘッダーを付けられます。キャッシュ制御に便利です。

                                    -
                                    -svr.set_mount_point("/", "./public", {
                                    -    {"Cache-Control", "max-age=3600"}
                                    -});
                                    -
                                    -
                                    -svr.set_mount_point("/", "./public", {
                                    -    {"Cache-Control", "max-age=3600"}
                                    -});
                                    -
                                    -
                                    -

                                    こうすると、ブラウザは配信されたファイルを1時間キャッシュします。

                                    -

                                    静的ファイルサーバー用のDockerファイル

                                    -

                                    cpp-httplibのリポジトリには、静的ファイルサーバー用の Dockerfile が含まれています。Docker Hubにビルド済みイメージも公開しているので、1コマンドで起動できます。

                                    -
                                    -> docker run -p 8080:80 -v ./my-site:/html yhirose4dockerhub/cpp-httplib-server
                                    -Serving HTTP on 0.0.0.0:80
                                    -Mount point: / -> ./html
                                    -Press Ctrl+C to shutdown gracefully...
                                    -192.168.65.1 - - [22/Feb/2026:12:00:00 +0000] "GET / HTTP/1.1" 200 256 "-" "Mozilla/5.0 ..."
                                    -192.168.65.1 - - [22/Feb/2026:12:00:00 +0000] "GET /style.css HTTP/1.1" 200 1024 "-" "Mozilla/5.0 ..."
                                    -192.168.65.1 - - [22/Feb/2026:12:00:01 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
                                    -
                                    -
                                    -> docker run -p 8080:80 -v ./my-site:/html yhirose4dockerhub/cpp-httplib-server
                                    -Serving HTTP on 0.0.0.0:80
                                    -Mount point: / -> ./html
                                    -Press Ctrl+C to shutdown gracefully...
                                    -192.168.65.1 - - [22/Feb/2026:12:00:00 +0000] "GET / HTTP/1.1" 200 256 "-" "Mozilla/5.0 ..."
                                    -192.168.65.1 - - [22/Feb/2026:12:00:00 +0000] "GET /style.css HTTP/1.1" 200 1024 "-" "Mozilla/5.0 ..."
                                    -192.168.65.1 - - [22/Feb/2026:12:00:01 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
                                    -
                                    -
                                    -

                                    ./my-site ディレクトリの中身が、そのままポート8080で配信されます。NGINXと同じログ形式で、アクセスの様子を確認できますよ。

                                    -

                                    次のステップ

                                    -

                                    静的ファイルの配信ができるようになりましたね。HTMLやCSS、JavaScriptを配信するWebサーバーが、これだけのコードで作れます。

                                    -

                                    次は、HTTPSで暗号化通信をしてみましょう。まずはTLSライブラリのセットアップからです。

                                    -

                                    次: TLS Setup

                                    - -
                                    -
                                    - -
                                    - - - - -
                                    -
                                    -
                                    - - - ESC -
                                    -
                                      -
                                      -
                                      - - - - diff --git a/docs/ja/tour/05-tls-setup/index.html b/docs/ja/tour/05-tls-setup/index.html deleted file mode 100644 index 863265e..0000000 --- a/docs/ja/tour/05-tls-setup/index.html +++ /dev/null @@ -1,231 +0,0 @@ - - - - - - TLS Setup - cpp-httplib - - - - - -
                                      -
                                      - cpp-httplib v0.36.0 -
                                      - -
                                      - - - -
                                      - - -
                                      - -
                                      - -
                                      -
                                      - - - -
                                      - - -
                                      -
                                      -

                                      TLS Setup

                                      -

                                      ここまではHTTP(平文)でやってきましたが、実際のWebではHTTPS(暗号化通信)が当たり前ですよね。cpp-httplibでHTTPSを使うには、TLSライブラリが必要です。

                                      -

                                      このTourではOpenSSLを使います。最も広く使われていて、情報も豊富です。

                                      -

                                      OpenSSLのインストール

                                      -

                                      お使いのOSに合わせてインストールしましょう。

                                      - - - - -
                                      OSインストール方法
                                      macOSHomebrew (brew install openssl)
                                      Ubuntu / Debiansudo apt install libssl-dev
                                      Windowsvcpkg (vcpkg install openssl)
                                      -

                                      コンパイルオプション

                                      -

                                      TLS機能を有効にするには、CPPHTTPLIB_OPENSSL_SUPPORT マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。

                                      -
                                      -# macOS (Homebrew)
                                      -clang++ -std=c++17 -DCPPHTTPLIB_OPENSSL_SUPPORT \
                                      -    -I$(brew --prefix openssl)/include \
                                      -    -L$(brew --prefix openssl)/lib \
                                      -    -lssl -lcrypto \
                                      -    -framework CoreFoundation -framework Security \
                                      -    -o server server.cpp
                                      -
                                      -# Linux
                                      -clang++ -std=c++17 -pthread -DCPPHTTPLIB_OPENSSL_SUPPORT \
                                      -    -lssl -lcrypto \
                                      -    -o server server.cpp
                                      -
                                      -# Windows (Developer Command Prompt)
                                      -cl /EHsc /std:c++17 /DCPPHTTPLIB_OPENSSL_SUPPORT server.cpp libssl.lib libcrypto.lib
                                      -
                                      -
                                      -# macOS (Homebrew)
                                      -clang++ -std=c++17 -DCPPHTTPLIB_OPENSSL_SUPPORT \
                                      -    -I$(brew --prefix openssl)/include \
                                      -    -L$(brew --prefix openssl)/lib \
                                      -    -lssl -lcrypto \
                                      -    -framework CoreFoundation -framework Security \
                                      -    -o server server.cpp
                                      -
                                      -# Linux
                                      -clang++ -std=c++17 -pthread -DCPPHTTPLIB_OPENSSL_SUPPORT \
                                      -    -lssl -lcrypto \
                                      -    -o server server.cpp
                                      -
                                      -# Windows (Developer Command Prompt)
                                      -cl /EHsc /std:c++17 /DCPPHTTPLIB_OPENSSL_SUPPORT server.cpp libssl.lib libcrypto.lib
                                      -
                                      -
                                      -

                                      それぞれのオプションの役割を見てみましょう。

                                      -
                                        -
                                      • -DCPPHTTPLIB_OPENSSL_SUPPORT — TLS機能を有効にするマクロ定義
                                      • -
                                      • -lssl -lcrypto — OpenSSLのライブラリをリンク
                                      • -
                                      • -I / -L(macOSのみ)— Homebrew版OpenSSLのパスを指定
                                      • -
                                      • -framework CoreFoundation -framework Security(macOSのみ)— Keychainからシステム証明書を自動で読み込むために必要です
                                      • -
                                      -

                                      動作確認

                                      -

                                      ちゃんと動くか確認してみましょう。httplib::Client にHTTPSのURLを渡してアクセスするだけのプログラムです。

                                      -
                                      -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                      -#include "httplib.h"
                                      -#include <iostream>
                                      -
                                      -int main() {
                                      -    httplib::Client cli("https://www.google.com");
                                      -
                                      -    auto res = cli.Get("/");
                                      -    if (res) {
                                      -        std::cout << "Status: " << res->status << std::endl;
                                      -    } else {
                                      -        std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
                                      -    }
                                      -}
                                      -
                                      -
                                      -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                      -#include "httplib.h"
                                      -#include <iostream>
                                      -
                                      -int main() {
                                      -    httplib::Client cli("https://www.google.com");
                                      -
                                      -    auto res = cli.Get("/");
                                      -    if (res) {
                                      -        std::cout << "Status: " << res->status << std::endl;
                                      -    } else {
                                      -        std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
                                      -    }
                                      -}
                                      -
                                      -
                                      -

                                      コンパイルして実行してみてください。Status: 200 と表示されれば、セットアップ完了です。

                                      -

                                      他のTLSバックエンド

                                      -

                                      cpp-httplibはOpenSSL以外にも、Mbed TLSとwolfSSLに対応しています。マクロ定義とリンクするライブラリを変えるだけで切り替えられます。

                                      - - - - -
                                      バックエンドマクロ定義リンクするライブラリ
                                      OpenSSLCPPHTTPLIB_OPENSSL_SUPPORTlibssl, libcrypto
                                      Mbed TLSCPPHTTPLIB_MBEDTLS_SUPPORTlibmbedtls, libmbedx509, libmbedcrypto
                                      wolfSSLCPPHTTPLIB_WOLFSSL_SUPPORTlibwolfssl
                                      -

                                      このTourではOpenSSLを前提に進めますが、APIはどのバックエンドでも共通です。

                                      -

                                      次のステップ

                                      -

                                      TLSの準備ができましたね。次は、HTTPSサイトにリクエストを送ってみましょう。

                                      -

                                      次: HTTPS Client

                                      - -
                                      -
                                      - -
                                      - - - - -
                                      -
                                      -
                                      - - - ESC -
                                      -
                                        -
                                        -
                                        - - - - diff --git a/docs/ja/tour/06-https-client/index.html b/docs/ja/tour/06-https-client/index.html deleted file mode 100644 index 8a0915b..0000000 --- a/docs/ja/tour/06-https-client/index.html +++ /dev/null @@ -1,289 +0,0 @@ - - - - - - HTTPS Client - cpp-httplib - - - - - -
                                        -
                                        - cpp-httplib v0.36.0 -
                                        - -
                                        - - - -
                                        - - -
                                        - -
                                        - -
                                        -
                                        - - - -
                                        - - -
                                        -
                                        -

                                        HTTPS Client

                                        -

                                        前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った httplib::Client がそのまま使えます。コンストラクタに https:// 付きのURLを渡すだけです。

                                        -

                                        GETリクエスト

                                        -

                                        実在するHTTPSサイトにアクセスしてみましょう。

                                        -
                                        -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                        -#include "httplib.h"
                                        -#include <iostream>
                                        -
                                        -int main() {
                                        -    httplib::Client cli("https://nghttp2.org");
                                        -
                                        -    auto res = cli.Get("/");
                                        -    if (res) {
                                        -        std::cout << res->status << std::endl;           // 200
                                        -        std::cout << res->body.substr(0, 100) << std::endl;  // HTMLの先頭部分
                                        -    } else {
                                        -        std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
                                        -    }
                                        -}
                                        -
                                        -
                                        -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                        -#include "httplib.h"
                                        -#include <iostream>
                                        -
                                        -int main() {
                                        -    httplib::Client cli("https://nghttp2.org");
                                        -
                                        -    auto res = cli.Get("/");
                                        -    if (res) {
                                        -        std::cout << res->status << std::endl;           // 200
                                        -        std::cout << res->body.substr(0, 100) << std::endl;  // HTMLの先頭部分
                                        -    } else {
                                        -        std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
                                        -    }
                                        -}
                                        -
                                        -
                                        -

                                        2章では httplib::Client cli("http://localhost:8080") と書きましたよね。スキームを https:// に変えるだけです。Get()Post() など、2章で学んだAPIはすべてそのまま使えます。

                                        -
                                        -curl https://nghttp2.org/
                                        -
                                        -
                                        -curl https://nghttp2.org/
                                        -
                                        -
                                        -

                                        ポートの指定

                                        -

                                        HTTPSのデフォルトポートは443です。別のポートを使いたい場合は、URLにポートを含めます。

                                        -
                                        -httplib::Client cli("https://localhost:8443");
                                        -
                                        -
                                        -httplib::Client cli("https://localhost:8443");
                                        -
                                        -
                                        -

                                        CA証明書の検証

                                        -

                                        httplib::Client はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。

                                        -

                                        CA証明書は、macOSならKeychain、LinuxならシステムのCA証明書ストア、WindowsならWindowsの証明書ストアから自動で読み込みます。ほとんどの場合、追加の設定は要りません。

                                        -

                                        CA証明書ファイルの指定

                                        -

                                        環境によってはシステムのCA証明書が見つからないこともあります。そのときは set_ca_cert_path() でパスを直接指定してください。

                                        -
                                        -httplib::Client cli("https://nghttp2.org");
                                        -cli.set_ca_cert_path("/etc/ssl/certs/ca-certificates.crt");
                                        -
                                        -auto res = cli.Get("/");
                                        -
                                        -
                                        -httplib::Client cli("https://nghttp2.org");
                                        -cli.set_ca_cert_path("/etc/ssl/certs/ca-certificates.crt");
                                        -
                                        -auto res = cli.Get("/");
                                        -
                                        -
                                        -curl --cacert /etc/ssl/certs/ca-certificates.crt https://nghttp2.org/
                                        -
                                        -
                                        -curl --cacert /etc/ssl/certs/ca-certificates.crt https://nghttp2.org/
                                        -
                                        -
                                        -

                                        証明書検証の無効化

                                        -

                                        開発中、自己署名証明書のサーバーに接続したいときは、検証を無効にできます。

                                        -
                                        -httplib::Client cli("https://localhost:8443");
                                        -cli.enable_server_certificate_verification(false);
                                        -
                                        -auto res = cli.Get("/");
                                        -
                                        -
                                        -httplib::Client cli("https://localhost:8443");
                                        -cli.enable_server_certificate_verification(false);
                                        -
                                        -auto res = cli.Get("/");
                                        -
                                        -
                                        -curl -k https://localhost:8443/
                                        -
                                        -
                                        -curl -k https://localhost:8443/
                                        -
                                        -
                                        -

                                        本番では絶対に無効にしないでください。中間者攻撃のリスクがあります。

                                        -

                                        リダイレクトの追跡

                                        -

                                        HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば http:// から https:// へ、あるいは www なしから www ありへ転送されるケースです。

                                        -

                                        デフォルトではリダイレクトを追跡しません。リダイレクト先は Location ヘッダーで確認できます。

                                        -
                                        -httplib::Client cli("https://nghttp2.org");
                                        -
                                        -auto res = cli.Get("/httpbin/redirect/3");
                                        -if (res) {
                                        -    std::cout << res->status << std::endl;  // 302
                                        -    std::cout << res->get_header_value("Location") << std::endl;
                                        -}
                                        -
                                        -
                                        -httplib::Client cli("https://nghttp2.org");
                                        -
                                        -auto res = cli.Get("/httpbin/redirect/3");
                                        -if (res) {
                                        -    std::cout << res->status << std::endl;  // 302
                                        -    std::cout << res->get_header_value("Location") << std::endl;
                                        -}
                                        -
                                        -
                                        -curl https://nghttp2.org/httpbin/redirect/3
                                        -
                                        -
                                        -curl https://nghttp2.org/httpbin/redirect/3
                                        -
                                        -
                                        -

                                        set_follow_location(true) を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。

                                        -
                                        -httplib::Client cli("https://nghttp2.org");
                                        -cli.set_follow_location(true);
                                        -
                                        -auto res = cli.Get("/httpbin/redirect/3");
                                        -if (res) {
                                        -    std::cout << res->status << std::endl;  // 200(最終的なレスポンス)
                                        -}
                                        -
                                        -
                                        -httplib::Client cli("https://nghttp2.org");
                                        -cli.set_follow_location(true);
                                        -
                                        -auto res = cli.Get("/httpbin/redirect/3");
                                        -if (res) {
                                        -    std::cout << res->status << std::endl;  // 200(最終的なレスポンス)
                                        -}
                                        -
                                        -
                                        -curl -L https://nghttp2.org/httpbin/redirect/3
                                        -
                                        -
                                        -curl -L https://nghttp2.org/httpbin/redirect/3
                                        -
                                        -
                                        -

                                        次のステップ

                                        -

                                        HTTPSクライアントの使い方がわかりましたね。次は自分でHTTPSサーバーを立ててみましょう。自己署名証明書の作り方から始めます。

                                        -

                                        次: HTTPS Server

                                        - -
                                        -
                                        - -
                                        - - - - -
                                        -
                                        -
                                        - - - ESC -
                                        -
                                          -
                                          -
                                          - - - - diff --git a/docs/ja/tour/07-https-server/index.html b/docs/ja/tour/07-https-server/index.html deleted file mode 100644 index 32c3d64..0000000 --- a/docs/ja/tour/07-https-server/index.html +++ /dev/null @@ -1,278 +0,0 @@ - - - - - - HTTPS Server - cpp-httplib - - - - - -
                                          -
                                          - cpp-httplib v0.36.0 -
                                          - -
                                          - - - -
                                          - - -
                                          - -
                                          - -
                                          -
                                          - - - -
                                          - - -
                                          -
                                          -

                                          HTTPS Server

                                          -

                                          前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の httplib::Serverhttplib::SSLServer に置き換えるだけです。

                                          -

                                          ただし、TLSサーバーにはサーバー証明書と秘密鍵が必要です。まずはそこから準備しましょう。

                                          -

                                          自己署名証明書の作成

                                          -

                                          開発やテスト用なら、自己署名証明書(いわゆるオレオレ証明書)で十分です。OpenSSLのコマンドでサクッと作れます。

                                          -
                                          -openssl req -x509 -noenc -keyout key.pem -out cert.pem -subj /CN=localhost
                                          -
                                          -
                                          -openssl req -x509 -noenc -keyout key.pem -out cert.pem -subj /CN=localhost
                                          -
                                          -
                                          -

                                          これで2つのファイルができます。

                                          -
                                            -
                                          • cert.pem — サーバー証明書
                                          • -
                                          • key.pem — 秘密鍵
                                          • -
                                          -

                                          最小のHTTPSサーバー

                                          -

                                          証明書ができたら、さっそくサーバーを書いてみましょう。

                                          -
                                          -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                          -#include "httplib.h"
                                          -#include <iostream>
                                          -
                                          -int main() {
                                          -    httplib::SSLServer svr("cert.pem", "key.pem");
                                          -
                                          -    svr.Get("/", [](const auto &, auto &res) {
                                          -        res.set_content("Hello, HTTPS!", "text/plain");
                                          -    });
                                          -
                                          -    std::cout << "Listening on https://localhost:8443" << std::endl;
                                          -    svr.listen("0.0.0.0", 8443);
                                          -}
                                          -
                                          -
                                          -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                          -#include "httplib.h"
                                          -#include <iostream>
                                          -
                                          -int main() {
                                          -    httplib::SSLServer svr("cert.pem", "key.pem");
                                          -
                                          -    svr.Get("/", [](const auto &, auto &res) {
                                          -        res.set_content("Hello, HTTPS!", "text/plain");
                                          -    });
                                          -
                                          -    std::cout << "Listening on https://localhost:8443" << std::endl;
                                          -    svr.listen("0.0.0.0", 8443);
                                          -}
                                          -
                                          -
                                          -

                                          httplib::SSLServer のコンストラクタに証明書と秘密鍵のパスを渡すだけです。ルーティングの書き方は3章の httplib::Server とまったく同じですよ。

                                          -

                                          コンパイルして起動しましょう。

                                          -

                                          動作確認

                                          -

                                          サーバーが起動したら、curl でアクセスしてみましょう。自己署名証明書なので、-k オプションで証明書検証をスキップします。

                                          -
                                          -curl -k https://localhost:8443/
                                          -# Hello, HTTPS!
                                          -
                                          -
                                          -curl -k https://localhost:8443/
                                          -# Hello, HTTPS!
                                          -
                                          -
                                          -

                                          ブラウザで https://localhost:8443 を開くと、「この接続は安全ではありません」と警告が出ます。自己署名証明書なので正常です。気にせず進めてください。

                                          -

                                          クライアントからの接続

                                          -

                                          前章の httplib::Client で接続してみましょう。自己署名証明書のサーバーに接続するには、2つの方法があります。

                                          -

                                          方法1: 証明書検証を無効にする

                                          -

                                          開発時の手軽な方法です。

                                          -
                                          -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                          -#include "httplib.h"
                                          -#include <iostream>
                                          -
                                          -int main() {
                                          -    httplib::Client cli("https://localhost:8443");
                                          -    cli.enable_server_certificate_verification(false);
                                          -
                                          -    auto res = cli.Get("/");
                                          -    if (res) {
                                          -        std::cout << res->body << std::endl;  // Hello, HTTPS!
                                          -    }
                                          -}
                                          -
                                          -
                                          -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                          -#include "httplib.h"
                                          -#include <iostream>
                                          -
                                          -int main() {
                                          -    httplib::Client cli("https://localhost:8443");
                                          -    cli.enable_server_certificate_verification(false);
                                          -
                                          -    auto res = cli.Get("/");
                                          -    if (res) {
                                          -        std::cout << res->body << std::endl;  // Hello, HTTPS!
                                          -    }
                                          -}
                                          -
                                          -
                                          -

                                          方法2: 自己署名証明書をCA証明書として指定する

                                          -

                                          こちらのほうが安全です。cert.pem をCA証明書として信頼するよう指定します。

                                          -
                                          -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                          -#include "httplib.h"
                                          -#include <iostream>
                                          -
                                          -int main() {
                                          -    httplib::Client cli("https://localhost:8443");
                                          -    cli.set_ca_cert_path("cert.pem");
                                          -
                                          -    auto res = cli.Get("/");
                                          -    if (res) {
                                          -        std::cout << res->body << std::endl;  // Hello, HTTPS!
                                          -    }
                                          -}
                                          -
                                          -
                                          -#define CPPHTTPLIB_OPENSSL_SUPPORT
                                          -#include "httplib.h"
                                          -#include <iostream>
                                          -
                                          -int main() {
                                          -    httplib::Client cli("https://localhost:8443");
                                          -    cli.set_ca_cert_path("cert.pem");
                                          -
                                          -    auto res = cli.Get("/");
                                          -    if (res) {
                                          -        std::cout << res->body << std::endl;  // Hello, HTTPS!
                                          -    }
                                          -}
                                          -
                                          -
                                          -

                                          この方法なら、指定した証明書のサーバーにだけ接続を許可して、なりすましを防げます。テスト環境でもなるべくこちらを使いましょう。

                                          -

                                          Server と SSLServer の比較

                                          -

                                          3章で学んだ httplib::Server のAPIは、httplib::SSLServer でもそのまま使えます。違いはコンストラクタだけです。

                                          - - - - - -
                                          httplib::Serverhttplib::SSLServer
                                          コンストラクタ引数なし証明書と秘密鍵のパス
                                          プロトコルHTTPHTTPS
                                          ポート(慣例)80808443
                                          ルーティング共通共通
                                          -

                                          HTTPサーバーをHTTPSに切り替えるには、コンストラクタを変えるだけです。

                                          -

                                          次のステップ

                                          -

                                          HTTPSサーバーが動きましたね。これでHTTP/HTTPSのクライアントとサーバー、両方の基本がそろいました。

                                          -

                                          次は、cpp-httplibに新しく加わったWebSocket機能を見てみましょう。

                                          -

                                          次: WebSocket

                                          - -
                                          -
                                          - -
                                          - - - - -
                                          -
                                          -
                                          - - - ESC -
                                          -
                                            -
                                            -
                                            - - - - diff --git a/docs/ja/tour/08-websocket/index.html b/docs/ja/tour/08-websocket/index.html deleted file mode 100644 index 197e5b7..0000000 --- a/docs/ja/tour/08-websocket/index.html +++ /dev/null @@ -1,330 +0,0 @@ - - - - - - WebSocket - cpp-httplib - - - - - -
                                            -
                                            - cpp-httplib v0.36.0 -
                                            - -
                                            - - - -
                                            - - -
                                            - -
                                            - -
                                            -
                                            - - - -
                                            - - -
                                            -
                                            -

                                            WebSocket

                                            -

                                            cpp-httplibはWebSocketにも対応しています。HTTPのリクエスト/レスポンスと違い、WebSocketはサーバーとクライアントが双方向にメッセージをやり取りできます。チャットやリアルタイム通知に便利です。

                                            -

                                            さっそく、エコーサーバーとクライアントを作ってみましょう。

                                            -

                                            エコーサーバー

                                            -

                                            受け取ったメッセージをそのまま返すエコーサーバーです。

                                            -
                                            -#include "httplib.h"
                                            -#include <iostream>
                                            -
                                            -int main() {
                                            -    httplib::Server svr;
                                            -
                                            -    svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                                            -        std::string msg;
                                            -        while (ws.read(msg)) {
                                            -            ws.send(msg);  // 受け取ったメッセージをそのまま返す
                                            -        }
                                            -    });
                                            -
                                            -    std::cout << "Listening on port 8080..." << std::endl;
                                            -    svr.listen("0.0.0.0", 8080);
                                            -}
                                            -
                                            -
                                            -#include "httplib.h"
                                            -#include <iostream>
                                            -
                                            -int main() {
                                            -    httplib::Server svr;
                                            -
                                            -    svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                                            -        std::string msg;
                                            -        while (ws.read(msg)) {
                                            -            ws.send(msg);  // 受け取ったメッセージをそのまま返す
                                            -        }
                                            -    });
                                            -
                                            -    std::cout << "Listening on port 8080..." << std::endl;
                                            -    svr.listen("0.0.0.0", 8080);
                                            -}
                                            -
                                            -
                                            -

                                            svr.WebSocket() でWebSocketハンドラーを登録します。3章の svr.Get()svr.Post() と同じ感覚ですね。

                                            -

                                            ハンドラーの中では、ws.read(msg) でメッセージを待ちます。接続が閉じられると read()false を返すので、ループを抜けます。ws.send(msg) でメッセージを送り返します。

                                            -

                                            クライアントからの接続

                                            -

                                            httplib::ws::WebSocketClient を使ってサーバーに接続してみましょう。

                                            -
                                            -#include "httplib.h"
                                            -#include <iostream>
                                            -
                                            -int main() {
                                            -    httplib::ws::WebSocketClient client("ws://localhost:8080/ws");
                                            -
                                            -    if (!client.connect()) {
                                            -        std::cout << "Connection failed" << std::endl;
                                            -        return 1;
                                            -    }
                                            -
                                            -    // メッセージを送信
                                            -    client.send("Hello, WebSocket!");
                                            -
                                            -    // サーバーからの応答を受信
                                            -    std::string msg;
                                            -    if (client.read(msg)) {
                                            -        std::cout << msg << std::endl;  // Hello, WebSocket!
                                            -    }
                                            -
                                            -    client.close();
                                            -}
                                            -
                                            -
                                            -#include "httplib.h"
                                            -#include <iostream>
                                            -
                                            -int main() {
                                            -    httplib::ws::WebSocketClient client("ws://localhost:8080/ws");
                                            -
                                            -    if (!client.connect()) {
                                            -        std::cout << "Connection failed" << std::endl;
                                            -        return 1;
                                            -    }
                                            -
                                            -    // メッセージを送信
                                            -    client.send("Hello, WebSocket!");
                                            -
                                            -    // サーバーからの応答を受信
                                            -    std::string msg;
                                            -    if (client.read(msg)) {
                                            -        std::cout << msg << std::endl;  // Hello, WebSocket!
                                            -    }
                                            -
                                            -    client.close();
                                            -}
                                            -
                                            -
                                            -

                                            コンストラクタには ws://host:port/path 形式のURLを渡します。connect() で接続を開始し、send()read() でメッセージをやり取りします。

                                            -

                                            テキストとバイナリ

                                            -

                                            WebSocketにはテキストとバイナリの2種類のメッセージがあります。read() の戻り値で区別できます。

                                            -
                                            -svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                                            -    std::string msg;
                                            -    httplib::ws::ReadResult ret;
                                            -    while ((ret = ws.read(msg))) {
                                            -        if (ret == httplib::ws::Binary) {
                                            -            ws.send(msg.data(), msg.size());  // バイナリとして送信
                                            -        } else {
                                            -            ws.send(msg);  // テキストとして送信
                                            -        }
                                            -    }
                                            -});
                                            -
                                            -
                                            -svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                                            -    std::string msg;
                                            -    httplib::ws::ReadResult ret;
                                            -    while ((ret = ws.read(msg))) {
                                            -        if (ret == httplib::ws::Binary) {
                                            -            ws.send(msg.data(), msg.size());  // バイナリとして送信
                                            -        } else {
                                            -            ws.send(msg);  // テキストとして送信
                                            -        }
                                            -    }
                                            -});
                                            -
                                            -
                                            -
                                              -
                                            • ws.send(const std::string &) — テキストメッセージとして送信
                                            • -
                                            • ws.send(const char *, size_t) — バイナリメッセージとして送信
                                            • -
                                            -

                                            クライアント側も同じAPIです。

                                            -

                                            リクエスト情報へのアクセス

                                            -

                                            ハンドラーの第1引数 req から、ハンドシェイク時のHTTPリクエスト情報を読み取れます。認証トークンの確認などに便利です。

                                            -
                                            -svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws) {
                                            -    auto token = req.get_header_value("Authorization");
                                            -    if (token.empty()) {
                                            -        ws.close(httplib::ws::CloseStatus::PolicyViolation, "unauthorized");
                                            -        return;
                                            -    }
                                            -
                                            -    std::string msg;
                                            -    while (ws.read(msg)) {
                                            -        ws.send(msg);
                                            -    }
                                            -});
                                            -
                                            -
                                            -svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws) {
                                            -    auto token = req.get_header_value("Authorization");
                                            -    if (token.empty()) {
                                            -        ws.close(httplib::ws::CloseStatus::PolicyViolation, "unauthorized");
                                            -        return;
                                            -    }
                                            -
                                            -    std::string msg;
                                            -    while (ws.read(msg)) {
                                            -        ws.send(msg);
                                            -    }
                                            -});
                                            -
                                            -
                                            -

                                            WSSで使う

                                            -

                                            HTTPS上のWebSocket(WSS)にも対応しています。サーバー側は httplib::SSLServer にWebSocketハンドラーを登録するだけです。

                                            -
                                            -httplib::SSLServer svr("cert.pem", "key.pem");
                                            -
                                            -svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                                            -    std::string msg;
                                            -    while (ws.read(msg)) {
                                            -        ws.send(msg);
                                            -    }
                                            -});
                                            -
                                            -svr.listen("0.0.0.0", 8443);
                                            -
                                            -
                                            -httplib::SSLServer svr("cert.pem", "key.pem");
                                            -
                                            -svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
                                            -    std::string msg;
                                            -    while (ws.read(msg)) {
                                            -        ws.send(msg);
                                            -    }
                                            -});
                                            -
                                            -svr.listen("0.0.0.0", 8443);
                                            -
                                            -
                                            -

                                            クライアント側は wss:// スキームを使います。

                                            -
                                            -httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
                                            -
                                            -
                                            -httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
                                            -
                                            -
                                            -

                                            次のステップ

                                            -

                                            WebSocketの基本がわかりましたね。ここまでで Tourは終わりです。

                                            -

                                            次のページでは、Tourで取り上げなかった機能をまとめて紹介します。

                                            -

                                            次: What's Next

                                            - -
                                            -
                                            - -
                                            - - - - -
                                            -
                                            -
                                            - - - ESC -
                                            -
                                              -
                                              -
                                              - - - - diff --git a/docs/ja/tour/09-whats-next/index.html b/docs/ja/tour/09-whats-next/index.html deleted file mode 100644 index add4f45..0000000 --- a/docs/ja/tour/09-whats-next/index.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - What's Next - cpp-httplib - - - - - -
                                              -
                                              - cpp-httplib v0.36.0 -
                                              - -
                                              - - - -
                                              - - -
                                              - -
                                              - -
                                              -
                                              - - - -
                                              - - -
                                              -
                                              -

                                              What's Next

                                              -

                                              Tourお疲れさまでした! cpp-httplibの基本はひと通り押さえましたね。でも、まだまだ便利な機能があります。Tourで取り上げなかった機能をカテゴリー別に紹介します。

                                              -

                                              Streaming API

                                              -

                                              LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。stream::Get() を使えば、データをチャンクごとに処理できます。

                                              -
                                              -httplib::Client cli("http://localhost:11434");
                                              -
                                              -auto result = httplib::stream::Get(cli, "/api/generate");
                                              -
                                              -if (result) {
                                              -    while (result.next()) {
                                              -        std::cout.write(result.data(), result.size());
                                              -    }
                                              -}
                                              -
                                              -
                                              -httplib::Client cli("http://localhost:11434");
                                              -
                                              -auto result = httplib::stream::Get(cli, "/api/generate");
                                              -
                                              -if (result) {
                                              -    while (result.next()) {
                                              -        std::cout.write(result.data(), result.size());
                                              -    }
                                              -}
                                              -
                                              -
                                              -

                                              Get()content_receiver コールバックを渡す方法もあります。こちらはKeep-Aliveと併用できます。

                                              -
                                              -httplib::Client cli("http://localhost:8080");
                                              -
                                              -cli.Get("/stream", [](const char *data, size_t len) {
                                              -    std::cout.write(data, len);
                                              -    return true;
                                              -});
                                              -
                                              -
                                              -httplib::Client cli("http://localhost:8080");
                                              -
                                              -cli.Get("/stream", [](const char *data, size_t len) {
                                              -    std::cout.write(data, len);
                                              -    return true;
                                              -});
                                              -
                                              -
                                              -

                                              サーバー側には set_content_provider()set_chunked_content_provider() があります。サイズがわかっているなら前者、不明なら後者を使ってください。

                                              -
                                              -// サイズ指定あり(Content-Length が設定される)
                                              -svr.Get("/file", [](const auto &, auto &res) {
                                              -    auto size = get_file_size("large.bin");
                                              -    res.set_content_provider(size, "application/octet-stream",
                                              -        [](size_t offset, size_t length, httplib::DataSink &sink) {
                                              -            // offset から length バイト分を送る
                                              -            return true;
                                              -        });
                                              -});
                                              -
                                              -// サイズ不明(Chunked Transfer Encoding)
                                              -svr.Get("/stream", [](const auto &, auto &res) {
                                              -    res.set_chunked_content_provider("text/plain",
                                              -        [](size_t offset, httplib::DataSink &sink) {
                                              -            sink.write("chunk\n", 6);
                                              -            return true;  // falseを返すと終了
                                              -        });
                                              -});
                                              -
                                              -
                                              -// サイズ指定あり(Content-Length が設定される)
                                              -svr.Get("/file", [](const auto &, auto &res) {
                                              -    auto size = get_file_size("large.bin");
                                              -    res.set_content_provider(size, "application/octet-stream",
                                              -        [](size_t offset, size_t length, httplib::DataSink &sink) {
                                              -            // offset から length バイト分を送る
                                              -            return true;
                                              -        });
                                              -});
                                              -
                                              -// サイズ不明(Chunked Transfer Encoding)
                                              -svr.Get("/stream", [](const auto &, auto &res) {
                                              -    res.set_chunked_content_provider("text/plain",
                                              -        [](size_t offset, httplib::DataSink &sink) {
                                              -            sink.write("chunk\n", 6);
                                              -            return true;  // falseを返すと終了
                                              -        });
                                              -});
                                              -
                                              -
                                              -

                                              大きなファイルのアップロードには make_file_provider() が便利です。ファイルを全部メモリに読み込まず、ストリーミングで送れます。

                                              -
                                              -httplib::Client cli("http://localhost:8080");
                                              -
                                              -auto res = cli.Post("/upload", {}, {
                                              -    httplib::make_file_provider("file", "/path/to/large-file.zip")
                                              -});
                                              -
                                              -
                                              -httplib::Client cli("http://localhost:8080");
                                              -
                                              -auto res = cli.Post("/upload", {}, {
                                              -    httplib::make_file_provider("file", "/path/to/large-file.zip")
                                              -});
                                              -
                                              -
                                              -

                                              Server-Sent Events (SSE)

                                              -

                                              SSEクライアントも用意しています。自動再接続や Last-Event-ID による再開にも対応しています。

                                              -
                                              -httplib::Client cli("http://localhost:8080");
                                              -httplib::sse::SSEClient sse(cli, "/events");
                                              -
                                              -sse.on_message([](const httplib::sse::SSEMessage &msg) {
                                              -    std::cout << msg.event << ": " << msg.data << std::endl;
                                              -});
                                              -
                                              -sse.start();  // ブロッキング、自動再接続あり
                                              -
                                              -
                                              -httplib::Client cli("http://localhost:8080");
                                              -httplib::sse::SSEClient sse(cli, "/events");
                                              -
                                              -sse.on_message([](const httplib::sse::SSEMessage &msg) {
                                              -    std::cout << msg.event << ": " << msg.data << std::endl;
                                              -});
                                              -
                                              -sse.start();  // ブロッキング、自動再接続あり
                                              -
                                              -
                                              -

                                              イベントタイプごとにハンドラーを分けることもできますよ。

                                              -
                                              -sse.on_event("update", [](const httplib::sse::SSEMessage &msg) {
                                              -    // "update" イベントだけ処理
                                              -});
                                              -
                                              -
                                              -sse.on_event("update", [](const httplib::sse::SSEMessage &msg) {
                                              -    // "update" イベントだけ処理
                                              -});
                                              -
                                              -
                                              -

                                              認証

                                              -

                                              クライアントにはBasic認証、Bearer Token認証、Digest認証のヘルパーを用意しています。

                                              -
                                              -httplib::Client cli("https://api.example.com");
                                              -cli.set_basic_auth("user", "password");
                                              -cli.set_bearer_token_auth("my-token");
                                              -
                                              -
                                              -httplib::Client cli("https://api.example.com");
                                              -cli.set_basic_auth("user", "password");
                                              -cli.set_bearer_token_auth("my-token");
                                              -
                                              -
                                              -

                                              圧縮

                                              -

                                              gzip、Brotli、Zstandardによる圧縮・展開に対応しています。使いたい方式のマクロを定義してコンパイルしましょう。

                                              - - - - -
                                              圧縮方式マクロ定義
                                              gzipCPPHTTPLIB_ZLIB_SUPPORT
                                              BrotliCPPHTTPLIB_BROTLI_SUPPORT
                                              ZstandardCPPHTTPLIB_ZSTD_SUPPORT
                                              -
                                              -httplib::Client cli("https://example.com");
                                              -cli.set_compress(true);    // リクエストボディを圧縮
                                              -cli.set_decompress(true);  // レスポンスボディを展開
                                              -
                                              -
                                              -httplib::Client cli("https://example.com");
                                              -cli.set_compress(true);    // リクエストボディを圧縮
                                              -cli.set_decompress(true);  // レスポンスボディを展開
                                              -
                                              -
                                              -

                                              プロキシ

                                              -

                                              HTTPプロキシ経由で接続できます。

                                              -
                                              -httplib::Client cli("https://example.com");
                                              -cli.set_proxy("proxy.example.com", 8080);
                                              -cli.set_proxy_basic_auth("user", "password");
                                              -
                                              -
                                              -httplib::Client cli("https://example.com");
                                              -cli.set_proxy("proxy.example.com", 8080);
                                              -cli.set_proxy_basic_auth("user", "password");
                                              -
                                              -
                                              -

                                              タイムアウト

                                              -

                                              接続・読み取り・書き込みのタイムアウトを個別に設定できます。

                                              -
                                              -httplib::Client cli("https://example.com");
                                              -cli.set_connection_timeout(5, 0);  // 5秒
                                              -cli.set_read_timeout(10, 0);       // 10秒
                                              -cli.set_write_timeout(10, 0);      // 10秒
                                              -
                                              -
                                              -httplib::Client cli("https://example.com");
                                              -cli.set_connection_timeout(5, 0);  // 5秒
                                              -cli.set_read_timeout(10, 0);       // 10秒
                                              -cli.set_write_timeout(10, 0);      // 10秒
                                              -
                                              -
                                              -

                                              Keep-Alive

                                              -

                                              同じサーバーに何度もリクエストするなら、Keep-Aliveを有効にしましょう。TCP接続を再利用するので効率的です。

                                              -
                                              -httplib::Client cli("https://example.com");
                                              -cli.set_keep_alive(true);
                                              -
                                              -
                                              -httplib::Client cli("https://example.com");
                                              -cli.set_keep_alive(true);
                                              -
                                              -
                                              -

                                              サーバーのミドルウェア

                                              -

                                              リクエスト処理の前後にフックを挟めます。

                                              -
                                              -svr.set_pre_routing_handler([](const auto &req, auto &res) {
                                              -    // すべてのリクエストの前に実行される
                                              -    return httplib::Server::HandlerResponse::Unhandled;  // 通常のルーティングに進む
                                              -});
                                              -
                                              -svr.set_post_routing_handler([](const auto &req, auto &res) {
                                              -    // レスポンスが返された後に実行される
                                              -    res.set_header("X-Server", "cpp-httplib");
                                              -});
                                              -
                                              -
                                              -svr.set_pre_routing_handler([](const auto &req, auto &res) {
                                              -    // すべてのリクエストの前に実行される
                                              -    return httplib::Server::HandlerResponse::Unhandled;  // 通常のルーティングに進む
                                              -});
                                              -
                                              -svr.set_post_routing_handler([](const auto &req, auto &res) {
                                              -    // レスポンスが返された後に実行される
                                              -    res.set_header("X-Server", "cpp-httplib");
                                              -});
                                              -
                                              -
                                              -

                                              req.user_data を使うと、ミドルウェアからハンドラーにデータを渡せます。認証トークンのデコード結果を共有するときに便利です。

                                              -
                                              -svr.set_pre_routing_handler([](const auto &req, auto &res) {
                                              -    req.user_data["auth_user"] = std::string("alice");
                                              -    return httplib::Server::HandlerResponse::Unhandled;
                                              -});
                                              -
                                              -svr.Get("/me", [](const auto &req, auto &res) {
                                              -    auto user = std::any_cast<std::string>(req.user_data.at("auth_user"));
                                              -    res.set_content("Hello, " + user, "text/plain");
                                              -});
                                              -
                                              -
                                              -svr.set_pre_routing_handler([](const auto &req, auto &res) {
                                              -    req.user_data["auth_user"] = std::string("alice");
                                              -    return httplib::Server::HandlerResponse::Unhandled;
                                              -});
                                              -
                                              -svr.Get("/me", [](const auto &req, auto &res) {
                                              -    auto user = std::any_cast<std::string>(req.user_data.at("auth_user"));
                                              -    res.set_content("Hello, " + user, "text/plain");
                                              -});
                                              -
                                              -
                                              -

                                              エラーや例外のハンドラーもカスタマイズできますよ。

                                              -
                                              -svr.set_error_handler([](const auto &req, auto &res) {
                                              -    res.set_content("Custom Error Page", "text/html");
                                              -});
                                              -
                                              -svr.set_exception_handler([](const auto &req, auto &res, std::exception_ptr ep) {
                                              -    res.status = 500;
                                              -    res.set_content("Internal Server Error", "text/plain");
                                              -});
                                              -
                                              -
                                              -svr.set_error_handler([](const auto &req, auto &res) {
                                              -    res.set_content("Custom Error Page", "text/html");
                                              -});
                                              -
                                              -svr.set_exception_handler([](const auto &req, auto &res, std::exception_ptr ep) {
                                              -    res.status = 500;
                                              -    res.set_content("Internal Server Error", "text/plain");
                                              -});
                                              -
                                              -
                                              -

                                              ロギング

                                              -

                                              サーバーでもクライアントでもロガーを設定できます。

                                              -
                                              -svr.set_logger([](const auto &req, const auto &res) {
                                              -    std::cout << req.method << " " << req.path << " " << res.status << std::endl;
                                              -});
                                              -
                                              -
                                              -svr.set_logger([](const auto &req, const auto &res) {
                                              -    std::cout << req.method << " " << req.path << " " << res.status << std::endl;
                                              -});
                                              -
                                              -
                                              -

                                              Unix Domain Socket

                                              -

                                              TCP以外に、Unix Domain Socketでの通信にも対応しています。同じマシン上のプロセス間通信に使えます。

                                              -
                                              -// サーバー
                                              -httplib::Server svr;
                                              -svr.set_address_family(AF_UNIX);
                                              -svr.listen("/tmp/httplib.sock", 0);
                                              -
                                              -
                                              -// サーバー
                                              -httplib::Server svr;
                                              -svr.set_address_family(AF_UNIX);
                                              -svr.listen("/tmp/httplib.sock", 0);
                                              -
                                              -
                                              -// クライアント
                                              -httplib::Client cli("http://localhost");
                                              -cli.set_address_family(AF_UNIX);
                                              -cli.set_hostname_addr_map({{"localhost", "/tmp/httplib.sock"}});
                                              -
                                              -auto res = cli.Get("/");
                                              -
                                              -
                                              -// クライアント
                                              -httplib::Client cli("http://localhost");
                                              -cli.set_address_family(AF_UNIX);
                                              -cli.set_hostname_addr_map({{"localhost", "/tmp/httplib.sock"}});
                                              -
                                              -auto res = cli.Get("/");
                                              -
                                              -
                                              -

                                              さらに詳しく

                                              -

                                              もっと詳しく知りたいときは、以下を参照してください。

                                              -
                                                -
                                              • Cookbook — よくあるユースケースのレシピ集
                                              • -
                                              • README — 全APIのリファレンス
                                              • -
                                              • README-sse — Server-Sent Eventsの使い方
                                              • -
                                              • README-stream — Streaming APIの使い方
                                              • -
                                              • README-websocket — WebSocketサーバーの使い方
                                              • -
                                              - -
                                              -
                                              - -
                                              - - - - -
                                              -
                                              -
                                              - - - ESC -
                                              -
                                                -
                                                -
                                                - - - - diff --git a/docs/ja/tour/index.html b/docs/ja/tour/index.html deleted file mode 100644 index 2c31798..0000000 --- a/docs/ja/tour/index.html +++ /dev/null @@ -1,143 +0,0 @@ - - - - - - A Tour of cpp-httplib - cpp-httplib - - - - - -
                                                -
                                                - cpp-httplib v0.36.0 -
                                                - -
                                                - - - -
                                                - - -
                                                - -
                                                - -
                                                -
                                                - - - -
                                                - - -
                                                -
                                                -

                                                A Tour of cpp-httplib

                                                -

                                                cpp-httplibの基本を、順番に学んでいくチュートリアルです。各章は前の章の内容を踏まえて進む構成なので、1章から順に読んでください。

                                                -
                                                  -
                                                1. Getting Started — httplib.h の入手とHello Worldサーバー
                                                2. -
                                                3. Basic Client — GET/POST・パスパラメーターのリクエスト送信
                                                4. -
                                                5. Basic Server — ルーティング、パスパラメーター、レスポンスの組み立て
                                                6. -
                                                7. Static File Server — 静的ファイルの配信
                                                8. -
                                                9. TLS Setup — OpenSSL / mbedTLS のセットアップ
                                                10. -
                                                11. HTTPS Client — HTTPSサイトへのリクエスト
                                                12. -
                                                13. HTTPS Server — HTTPSサーバーの構築
                                                14. -
                                                15. WebSocket — WebSocket通信の基本
                                                16. -
                                                17. What's Next — さらなる機能の紹介
                                                18. -
                                                - -
                                                -
                                                - -
                                                - - - - -
                                                -
                                                -
                                                - - - ESC -
                                                -
                                                  -
                                                  -
                                                  - - - - diff --git a/docs/js/main.js b/docs/js/main.js deleted file mode 100644 index 0f2a89f..0000000 --- a/docs/js/main.js +++ /dev/null @@ -1,297 +0,0 @@ -// Language selector -(function () { - var btn = document.querySelector('.lang-btn'); - var popup = document.querySelector('.lang-popup'); - if (!btn || !popup) return; - - btn.addEventListener('click', function (e) { - e.stopPropagation(); - popup.classList.toggle('open'); - }); - - document.addEventListener('click', function () { - popup.classList.remove('open'); - }); - - popup.addEventListener('click', function (e) { - var link = e.target.closest('[data-lang]'); - if (!link) return; - e.preventDefault(); - var lang = link.getAttribute('data-lang'); - localStorage.setItem('preferred-lang', lang); - var basePath = document.documentElement.getAttribute('data-base-path') || ''; - var path = window.location.pathname; - // Strip base path prefix, replace lang, then re-add base path - var pathWithoutBase = path.slice(basePath.length); - var newPath = basePath + pathWithoutBase.replace(/^\/[a-z]{2}\//, '/' + lang + '/'); - window.location.href = newPath; - }); -})(); - -// Theme toggle -(function () { - var btn = document.querySelector('.theme-toggle'); - if (!btn) return; - - // Feather Icons: sun (light mode) and moon (dark mode) - var sunSVG = ''; - var moonSVG = ''; - - function getTheme() { - var stored = localStorage.getItem('preferred-theme'); - if (stored) return stored; - return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'; - } - - function applyTheme(theme) { - if (theme === 'light') { - document.documentElement.setAttribute('data-theme', 'light'); - } else { - document.documentElement.removeAttribute('data-theme'); - } - btn.innerHTML = theme === 'light' ? sunSVG : moonSVG; - } - - applyTheme(getTheme()); - - btn.addEventListener('click', function () { - var current = getTheme(); - var next = current === 'dark' ? 'light' : 'dark'; - localStorage.setItem('preferred-theme', next); - applyTheme(next); - }); -})(); - -// Mobile sidebar toggle -(function () { - var toggle = document.querySelector('.sidebar-toggle'); - var sidebar = document.querySelector('.sidebar'); - if (!toggle || !sidebar) return; - - toggle.addEventListener('click', function () { - sidebar.classList.toggle('open'); - }); - - document.addEventListener('click', function (e) { - if (!sidebar.contains(e.target) && e.target !== toggle) { - sidebar.classList.remove('open'); - } - }); -})(); - -// Site search (⌘K / Ctrl+K) -(function () { - var overlay = document.getElementById('search-overlay'); - var input = document.getElementById('search-input'); - var resultsList = document.getElementById('search-results'); - if (!overlay || !input || !resultsList) return; - - var searchBtn = document.querySelector('.search-btn'); - var pagesData = null; // cached pages-data.json - var activeIndex = -1; - - function getCurrentLang() { - return document.documentElement.getAttribute('lang') || 'en'; - } - - function getBasePath() { - return document.documentElement.getAttribute('data-base-path') || ''; - } - - function openSearch() { - overlay.classList.add('open'); - input.value = ''; - resultsList.innerHTML = ''; - activeIndex = -1; - input.focus(); - loadPagesData(); - } - - function closeSearch() { - overlay.classList.remove('open'); - input.value = ''; - resultsList.innerHTML = ''; - activeIndex = -1; - } - - function loadPagesData() { - if (pagesData) return; - var basePath = getBasePath(); - fetch(basePath + '/pages-data.json') - .then(function (res) { return res.json(); }) - .then(function (data) { pagesData = data; }) - .catch(function () { pagesData = []; }); - } - - function escapeRegExp(s) { - return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - } - - function highlightText(text, query) { - if (!query) return text; - var escaped = escapeRegExp(query); - var re = new RegExp('(' + escaped + ')', 'gi'); - return text.replace(re, '$1'); - } - - function buildSnippet(body, query) { - if (!query || !body) return ''; - var lower = body.toLowerCase(); - var idx = lower.indexOf(query.toLowerCase()); - var start, end, snippet; - if (idx === -1) { - snippet = body.substring(0, 120); - } else { - start = Math.max(0, idx - 40); - end = Math.min(body.length, idx + query.length + 80); - snippet = (start > 0 ? '...' : '') + body.substring(start, end) + (end < body.length ? '...' : ''); - } - return highlightText(snippet, query); - } - - function search(query) { - if (!pagesData || !query) { - resultsList.innerHTML = ''; - activeIndex = -1; - return; - } - - var lang = getCurrentLang(); - var q = query.toLowerCase(); - - // Score and filter - var scored = []; - for (var i = 0; i < pagesData.length; i++) { - var page = pagesData[i]; - if (page.lang !== lang) continue; - - var score = 0; - var titleLower = page.title.toLowerCase(); - var bodyLower = (page.body || '').toLowerCase(); - - if (titleLower.indexOf(q) !== -1) { - score += 10; - // Bonus for exact title match - if (titleLower === q) score += 5; - } - if (bodyLower.indexOf(q) !== -1) { - score += 3; - } - if (page.section.toLowerCase().indexOf(q) !== -1) { - score += 1; - } - - if (score > 0) { - scored.push({ page: page, score: score }); - } - } - - // Sort by score descending - scored.sort(function (a, b) { return b.score - a.score; }); - - // Limit results - var results = scored.slice(0, 20); - - if (results.length === 0) { - resultsList.innerHTML = '
                                                • No results found.
                                                • '; - activeIndex = -1; - return; - } - - var html = ''; - for (var j = 0; j < results.length; j++) { - var r = results[j]; - var snippet = buildSnippet(r.page.body, query); - html += '
                                                • ' - + '
                                                  ' + highlightText(r.page.title, query) + '
                                                  ' - + (snippet ? '
                                                  ' + snippet + '
                                                  ' : '') - + '
                                                • '; - } - resultsList.innerHTML = html; - activeIndex = -1; - } - - function setActive(index) { - var items = resultsList.querySelectorAll('li[data-url]'); - if (items.length === 0) return; - // Remove previous active - for (var i = 0; i < items.length; i++) { - items[i].classList.remove('active'); - } - if (index < 0) index = items.length - 1; - if (index >= items.length) index = 0; - activeIndex = index; - items[activeIndex].classList.add('active'); - items[activeIndex].scrollIntoView({ block: 'nearest' }); - } - - function navigateToActive() { - var items = resultsList.querySelectorAll('li[data-url]'); - if (activeIndex >= 0 && activeIndex < items.length) { - var url = items[activeIndex].getAttribute('data-url'); - if (url) { - closeSearch(); - window.location.href = url; - } - } - } - - // Event: search button - if (searchBtn) { - searchBtn.addEventListener('click', function (e) { - e.stopPropagation(); - openSearch(); - }); - } - - // Use capture phase to intercept keys before browser default behavior - // (e.g. ESC clearing input text in some browsers) - document.addEventListener('keydown', function (e) { - if ((e.metaKey || e.ctrlKey) && e.key === 'k') { - e.preventDefault(); - overlay.classList.contains('open') ? closeSearch() : openSearch(); - return; - } - if (!overlay.classList.contains('open')) return; - if (e.key === 'Escape') { - e.preventDefault(); - closeSearch(); - } else if (e.key === 'ArrowDown') { - e.preventDefault(); - setActive(activeIndex + 1); - } else if (e.key === 'ArrowUp') { - e.preventDefault(); - setActive(activeIndex - 1); - } else if (e.key === 'Enter') { - e.preventDefault(); - navigateToActive(); - } - }, true); // capture phase - - // Event: click overlay background to close - overlay.addEventListener('click', function (e) { - if (e.target === overlay) { - closeSearch(); - } - }); - - // Event: click result item - resultsList.addEventListener('click', function (e) { - var li = e.target.closest('li[data-url]'); - if (!li) return; - var url = li.getAttribute('data-url'); - if (url) { - closeSearch(); - window.location.href = url; - } - }); - - // Event: input for live search - var debounceTimer = null; - input.addEventListener('input', function () { - clearTimeout(debounceTimer); - debounceTimer = setTimeout(function () { - search(input.value.trim()); - }, 150); - }); -})(); diff --git a/docs/pages-data.json b/docs/pages-data.json deleted file mode 100644 index aa9b798..0000000 --- a/docs/pages-data.json +++ /dev/null @@ -1 +0,0 @@ -[{"title":"Cookbook","url":"/cpp-httplib/en/cookbook/","lang":"en","section":"cookbook","body":"This section is under construction. Check back soon for a collection of recipes organized by topic."},{"title":"cpp-httplib","url":"/cpp-httplib/en/","lang":"en","section":"","body":"cpp-httplib is an HTTP/HTTPS library for C++. Just copy a single header file, httplib.h , and you're ready to go. When you need a quick HTTP server or client in C++, you want something that just works. That's exactly why I built cpp-httplib. You can start writing both servers and clients in just a few lines of code. The API uses a lambda-based design that feels natural. It runs anywhere you have a C++11 or later compiler. Windows, macOS, Linux — use whatever environment you already have. HTTPS w"},{"title":"Static File Server","url":"/cpp-httplib/en/tour/04-static-file-server/","lang":"en","section":"tour","body":"cpp-httplib can serve static files too — HTML, CSS, images, you name it. No complicated configuration required. One call to set_mount_point() is all it takes. The basics of set_mount_point Let's jump right in. set_mount_point() maps a URL path to a local directory. #include " httplib.h " #include < iostream > int main () { httplib::Server svr; svr. set_mount_point (" / ", " ./html "); std::cout << " Listening on port 8080... " << std::end"},{"title":"Getting Started","url":"/cpp-httplib/en/tour/01-getting-started/","lang":"en","section":"tour","body":"All you need to get started with cpp-httplib is httplib.h and a C++ compiler. Let's download the file and get a Hello World server running. Getting httplib.h You can download it directly from GitHub. Always use the latest version. curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h Place the downloaded httplib.h in your project directory and you're good to go. Setting Up Your Compiler OS Development Environment Setup macOS Apple Clang Xcode Command Line Tools ( xcode-s"},{"title":"Basic Server","url":"/cpp-httplib/en/tour/03-basic-server/","lang":"en","section":"tour","body":"In the previous chapter, you sent requests from a client to a test server. Now let's walk through how that server actually works. Starting the Server Once you've registered your routes, call svr.listen() to start the server. svr. listen (" 0.0.0.0 ", 8080 ); The first argument is the host, and the second is the port. \"0.0.0.0\" listens on all network interfaces. Use \"127.0.0.1\" if you want to accept connections from your own machine only. listen() is a blocking call. It won't return unt"},{"title":"Basic Client","url":"/cpp-httplib/en/tour/02-basic-client/","lang":"en","section":"tour","body":"cpp-httplib isn't just for servers -- it also comes with a full HTTP client. Let's use httplib::Client to send GET and POST requests. Preparing a Test Server To try out the client, you need a server that accepts requests. Save the following code, then compile and run it the same way you did in the previous chapter. We'll cover the server details in the next chapter. #include " httplib.h " #include < iostream > int main () { httplib::Server svr; svr. Get (" /hi ", []( co"},{"title":"HTTPS Client","url":"/cpp-httplib/en/tour/06-https-client/","lang":"en","section":"tour","body":"In the previous chapter, you set up OpenSSL. Now let's put it to use with an HTTPS client. You can use the same httplib::Client from Chapter 2. Just pass a URL with the https:// scheme to the constructor. GET Request Let's try accessing a real HTTPS site. #define CPPHTTPLIB_OPENSSL_SUPPORT #include " httplib.h " #include < iostream > int main () { httplib::Client cli (" https://nghttp2.org "); auto res = cli. Get (" / "); if (res) { std::cout << res->"},{"title":"A Tour of cpp-httplib","url":"/cpp-httplib/en/tour/","lang":"en","section":"tour","body":"This is a step-by-step tutorial that walks you through the basics of cpp-httplib. Each chapter builds on the previous one, so please read them in order starting from Chapter 1. Getting Started — Get httplib.h and build a Hello World server Basic Client — Send GET/POST requests and use path parameters Basic Server — Routing, path parameters, and building responses Static File Server — Serve static files TLS Setup — Set up OpenSSL / mbedTLS HTTPS Client — Make requests to HTTPS sites HTTPS Server "},{"title":"What's Next","url":"/cpp-httplib/en/tour/09-whats-next/","lang":"en","section":"tour","body":"Great job finishing the Tour! You now have a solid grasp of the cpp-httplib basics. But there's a lot more to explore. Here's a quick overview of features we didn't cover in the Tour, organized by category. Streaming API When you're working with LLM streaming responses or downloading large files, you don't want to load the entire response into memory. Use stream::Get() to process data chunk by chunk. httplib::Client cli (" http://localhost:11434 "); auto result = httplib::stream::Get ("},{"title":"TLS Setup","url":"/cpp-httplib/en/tour/05-tls-setup/","lang":"en","section":"tour","body":"So far we've been using plain HTTP, but in the real world, HTTPS is the norm. To use HTTPS with cpp-httplib, you need a TLS library. In this tour, we'll use OpenSSL. It's the most widely used option, and you'll find plenty of resources online. Installing OpenSSL Install it for your OS. OS How to install macOS Homebrew ( brew install openssl ) Ubuntu / Debian sudo apt install libssl-dev Windows vcpkg ( vcpkg install openssl ) Compile Options To enable TLS, define the CPPHTTPLIB_OPENSSL_SUPPORT ma"},{"title":"HTTPS Server","url":"/cpp-httplib/en/tour/07-https-server/","lang":"en","section":"tour","body":"In the previous chapter, you used an HTTPS client. Now let's set up your own HTTPS server. Just swap httplib::Server from Chapter 3 with httplib::SSLServer . A TLS server needs a server certificate and a private key, though. Let's get those ready first. Creating a Self-Signed Certificate For development and testing, a self-signed certificate works just fine. You can generate one quickly with an OpenSSL command. openssl req -x509 -noenc -keyout key.pem -out cert.pem -subj /CN=localhost This creat"},{"title":"WebSocket","url":"/cpp-httplib/en/tour/08-websocket/","lang":"en","section":"tour","body":"cpp-httplib supports WebSocket as well. Unlike HTTP request/response, WebSocket lets the server and client exchange messages in both directions. It's great for chat apps and real-time notifications. Let's build an echo server and client right away. Echo Server Here's an echo server that sends back whatever message it receives. #include " httplib.h " #include < iostream > int main () { httplib::Server svr; svr. WebSocket (" /ws ", []( const httplib::Request &, httpli"},{"title":"Cookbook","url":"/cpp-httplib/ja/cookbook/","lang":"ja","section":"cookbook","body":"This section is under construction. Check back soon for a collection of recipes organized by topic."},{"title":"cpp-httplib","url":"/cpp-httplib/ja/","lang":"ja","section":"","body":"cpp-httplib は、C++用のHTTP/HTTPSライブラリです。 httplib.h というヘッダーファイルを1枚コピーするだけで使えます。 C++でちょっとしたHTTPサーバーやクライアントが必要になったとき、すぐに動くものが欲しいですよね。cpp-httplibはまさにそのために作られました。サーバーもクライアントも、数行のコードで書き始められます。 APIはラムダ式をベースにした直感的な設計で、C++11以降のコンパイラーがあればどこでも動きます。Windows、macOS、Linux — お使いの環境をそのまま使えます。 HTTPSも使えます。OpenSSLやmbedTLSをリンクするだけで、サーバー・クライアントの両方がTLSに対応します。Content-Encoding(gzip, brotli等)、ファイルアップロードなど、実際の開発で必要になる機能もひと通り揃っています。WebSocketもサポートしています。 内部的にはブロッキングI/Oとスレッドプールを使っています。大量の同時接続を捌くような用途には向きませんが、APIサーバーやツールの組み込みHTTP、"},{"title":"Static File Server","url":"/cpp-httplib/ja/tour/04-static-file-server/","lang":"ja","section":"tour","body":"cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。 set_mount_point() を1行呼ぶだけです。 set_mount_point の基本 さっそくやってみましょう。 set_mount_point() は、URLのパスとローカルディレクトリを紐づけます。 #include " httplib.h " #include < iostream > int main () { httplib::Server svr; svr. set_mount_point (" / ", " ./html "); std::cout << " Listening on port 8080... " << std::endl; svr. listen (" 0.0.0.0 ", 8080 ); } 第1引数がURLのマウントポイント、第2引数がローカルのディレクトリパスです。この例だと、 / へのリ"},{"title":"Getting Started","url":"/cpp-httplib/ja/tour/01-getting-started/","lang":"ja","section":"tour","body":"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 サー"},{"title":"Basic Server","url":"/cpp-httplib/ja/tour/03-basic-server/","lang":"ja","section":"tour","body":"前章ではクライアントからリクエストを送りました。そのとき、テスト用サーバーを用意しましたね。この章では、あのサーバーの仕組みをひとつずつ紐解いていきます。 サーバーの起動 ルーティングを登録したら、最後に svr.listen() を呼んでサーバーを起動します。 svr. listen (" 0.0.0.0 ", 8080 ); 第1引数はホスト、第2引数はポート番号です。 \"0.0.0.0\" を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは \"127.0.0.1\" を使います。 listen() はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで Ctrl+C を押すか、別スレッドから svr.stop() を呼ぶまでサーバーは動き続けます。 ルーティング サーバーの核になるのは「ルーティング」です。どのURLに、どのHTTPメソッドでアクセスされたら、何をするか。それを登録する仕組みです。 httplib::Server svr; svr. G"},{"title":"Basic Client","url":"/cpp-httplib/ja/tour/02-basic-client/","lang":"ja","section":"tour","body":"cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。 httplib::Client を使って、GETやPOSTリクエストを送ってみましょう。 テスト用サーバーの準備 クライアントの動作を確認するために、リクエストを受け付けるサーバーを用意します。次のコードを保存し、前章と同じ手順でコンパイル・実行してください。サーバーの詳しい解説は次章で行います。 #include " httplib.h " #include < iostream > int main () { httplib::Server svr; svr. Get (" /hi ", []( const auto &, auto &res) { res. set_content (" Hello! ", " text/plain "); }); svr. Get (" /search ", []( const auto &req, auto &res)"},{"title":"HTTPS Client","url":"/cpp-httplib/ja/tour/06-https-client/","lang":"ja","section":"tour","body":"前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った httplib::Client がそのまま使えます。コンストラクタに https:// 付きのURLを渡すだけです。 GETリクエスト 実在するHTTPSサイトにアクセスしてみましょう。 #define CPPHTTPLIB_OPENSSL_SUPPORT #include " httplib.h " #include < iostream > int main () { httplib::Client cli (" https://nghttp2.org "); auto res = cli. Get (" / "); if (res) { std::cout << res-> status << std::endl; // 200 std::cout << res-> body . substr ( 0 , 100 ) << std::end"},{"title":"A Tour of cpp-httplib","url":"/cpp-httplib/ja/tour/","lang":"ja","section":"tour","body":"cpp-httplibの基本を、順番に学んでいくチュートリアルです。各章は前の章の内容を踏まえて進む構成なので、1章から順に読んでください。 Getting Started — httplib.h の入手とHello Worldサーバー Basic Client — GET/POST・パスパラメーターのリクエスト送信 Basic Server — ルーティング、パスパラメーター、レスポンスの組み立て Static File Server — 静的ファイルの配信 TLS Setup — OpenSSL / mbedTLS のセットアップ HTTPS Client — HTTPSサイトへのリクエスト HTTPS Server — HTTPSサーバーの構築 WebSocket — WebSocket通信の基本 What's Next — さらなる機能の紹介"},{"title":"What's Next","url":"/cpp-httplib/ja/tour/09-whats-next/","lang":"ja","section":"tour","body":"Tourお疲れさまでした! cpp-httplibの基本はひと通り押さえましたね。でも、まだまだ便利な機能があります。Tourで取り上げなかった機能をカテゴリー別に紹介します。 Streaming API LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。 stream::Get() を使えば、データをチャンクごとに処理できます。 httplib::Client cli (" http://localhost:11434 "); auto result = httplib::stream::Get (cli, " /api/generate "); if (result) { while (result. next ()) { std::cout. write (result. data (), result. size ()); } } Get() に content_receiver コールバックを渡す方法もあります。こちらはKeep-Aliveと併用できます。 httplib::Cl"},{"title":"TLS Setup","url":"/cpp-httplib/ja/tour/05-tls-setup/","lang":"ja","section":"tour","body":"ここまではHTTP(平文)でやってきましたが、実際のWebではHTTPS(暗号化通信)が当たり前ですよね。cpp-httplibでHTTPSを使うには、TLSライブラリが必要です。 このTourではOpenSSLを使います。最も広く使われていて、情報も豊富です。 OpenSSLのインストール お使いのOSに合わせてインストールしましょう。 OS インストール方法 macOS Homebrew ( brew install openssl ) Ubuntu / Debian sudo apt install libssl-dev Windows vcpkg ( vcpkg install openssl ) コンパイルオプション TLS機能を有効にするには、 CPPHTTPLIB_OPENSSL_SUPPORT マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。 # macOS (Homebrew) clang++ -std =c++17 -DCPPHTTPLIB_OPENSSL_SUPPORT \\ -I $ ( brew --prefix "},{"title":"HTTPS Server","url":"/cpp-httplib/ja/tour/07-https-server/","lang":"ja","section":"tour","body":"前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の httplib::Server を httplib::SSLServer に置き換えるだけです。 ただし、TLSサーバーにはサーバー証明書と秘密鍵が必要です。まずはそこから準備しましょう。 自己署名証明書の作成 開発やテスト用なら、自己署名証明書(いわゆるオレオレ証明書)で十分です。OpenSSLのコマンドでサクッと作れます。 openssl req -x509 -noenc -keyout key.pem -out cert.pem -subj /CN=localhost これで2つのファイルができます。 cert.pem — サーバー証明書 key.pem — 秘密鍵 最小のHTTPSサーバー 証明書ができたら、さっそくサーバーを書いてみましょう。 #define CPPHTTPLIB_OPENSSL_SUPPORT #include " httplib.h " #include < iostream > int main () { httplib:"},{"title":"WebSocket","url":"/cpp-httplib/ja/tour/08-websocket/","lang":"ja","section":"tour","body":"cpp-httplibはWebSocketにも対応しています。HTTPのリクエスト/レスポンスと違い、WebSocketはサーバーとクライアントが双方向にメッセージをやり取りできます。チャットやリアルタイム通知に便利です。 さっそく、エコーサーバーとクライアントを作ってみましょう。 エコーサーバー 受け取ったメッセージをそのまま返すエコーサーバーです。 #include " httplib.h " #include < iostream > int main () { httplib::Server svr; svr. WebSocket (" /ws ", []( const httplib::Request &, httplib::ws::WebSocket &ws) { std::string msg; while (ws. read (msg)) { ws. send (msg); // 受け取ったメッセージをそのまま返す } }); std::cout << " Listening on"}] \ No newline at end of file