Compare commits

..

55 Commits

Author SHA1 Message Date
yhirose 6f2717e623 Release v0.38.0 2026-03-14 23:17:13 -04:00
yhirose 257b266190 Add runtime configuration for WebSocket ping interval and related tests 2026-03-14 22:44:17 -04:00
yhirose ba0d0b82db Add benchmark tests and related configurations for performance evaluation 2026-03-14 22:16:53 -04:00
yhirose 5ecba74a99 Remove large data tests for GzipDecompressor and SSLClientServerTest due to memory issues 2026-03-14 21:50:55 -04:00
yhirose ec1ffbc27d Add Brotli compression support and corresponding tests 2026-03-14 21:42:48 -04:00
yhirose 4978f26f86 Fix port number in OpenStreamMalformedContentLength test to avoid conflicts 2026-03-14 20:59:15 -04:00
yhirose bb7c7ab075 Add quality parameter parsing for Accept-Encoding header and enhance encoding type selection logic 2026-03-14 20:51:25 -04:00
yhirose 1c3d35f83c Update comment to clarify requirements for safe handling in ClientImpl::handle_request 2026-03-14 19:27:51 -04:00
yhirose b1bb2b7ecc Implement setup_proxy_connection method for SSLClient and refactor proxy handling in open_stream 2026-03-14 19:26:31 -04:00
yhirose f6ed5fc60f Add SSL support for proxy connections in open_stream and corresponding test 2026-03-14 18:38:34 -04:00
yhirose 69d468f4d9 Enable BindDualStack test and remove disabled large content test due to memory issues 2026-03-14 18:22:27 -04:00
yhirose 2e61fd3e6e Update documentation to clarify progress callback usage and user data handling in examples 2026-03-13 22:54:29 -04:00
yhirose 3ad4a4243a Update .gitignore to include AGENTS.md and related documentation files 2026-03-13 22:31:44 -04:00
yhirose 511e3ef9e5 Update README.md to enhance TLS backend documentation and clarify platform-specific certificate handling 2026-03-13 22:30:05 -04:00
yhirose f787f31b87 Implement symlink protection in static file server and add corresponding tests 2026-03-13 16:22:16 -04:00
yhirose 43a54a3e3d Add tests for Unicode path component decoding in decode_path_component function 2026-03-13 00:32:41 -04:00
yhirose 83e98a28dd Add filename sanitization function and tests to prevent path traversal vulnerabilities 2026-03-13 00:29:13 -04:00
yhirose 4d7c9a788d Release v0.37.2 2026-03-13 00:11:00 -04:00
yhirose 1cd0347ace Refactor parse_port function to accept char pointer and length, improving flexibility and validation 2026-03-13 00:05:13 -04:00
yhirose b3a8af80b9 Add port validation and corresponding tests to prevent overflow and out-of-range values 2026-03-13 00:05:13 -04:00
yhirose 1e97c28e36 Implement request smuggling protection for duplicate Content-Length headers and add corresponding tests 2026-03-13 00:05:13 -04:00
yhirose d279eff4db Fix the proxy test error 2026-03-12 23:15:10 -04:00
yhirose 188035fb6d Add a test for the previous change 2026-03-12 22:57:11 -04:00
yhirose 125272f34b Fix TLS cert verification bypass on proxy redirect introduced in #2165 (#2396) 2026-03-12 21:54:51 -04:00
yhirose 9ced2f614d Fix #2395 2026-03-12 19:18:09 -04:00
yhirose 68fa9bce0f Release v0.37.1 2026-03-09 20:51:37 -04:00
yhirose 1f34c541b0 Add more books 2026-03-09 19:30:18 -04:00
yhirose e41ec36274 Fix handling of malformed Content-Length in open_stream and add tests 2026-03-08 22:30:20 -04:00
yhirose 7489fd3a8b Remove 32-bit limitation (#2388)
* Remove 32-bit limitation

* Fix build problems

* Add 32-bit disclaimer and fix MSVC x86 warnings

- Move 32-bit warning to top of README with strong disclaimer
- Add static_cast<size_t> to fix truncation warnings on 32-bit MSVC

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 23:07:21 -05:00
yhirose ab3098f18b Update README 2026-03-06 18:50:23 -05:00
yhirose 0d3a3d805c Release v0.37.0 2026-03-06 16:57:33 -05:00
yhirose a058e31a3a Use doc.yml to generate document site 2026-03-05 20:50:22 -05:00
yhirose c87d442aac Remove docs-gen 2026-03-03 23:58:03 -05:00
yhirose de296af3eb Fix problem with alternate file name check 2026-03-03 13:37:28 -05:00
yhirose 41899acece Release v0.36.0 2026-03-02 21:56:38 -05:00
yhirose bb22553087 Fix code format 2026-03-02 21:49:10 -05:00
yhirose 8bffbe3ff2 Merge commit from fork 2026-03-02 21:46:31 -05:00
yhirose 0e4f104141 Fix #2383 (#2385) 2026-03-02 21:09:31 -05:00
yhirose 74807d24a7 Update pages-data.json with new content and structure for cpp-httplib documentation 2026-03-02 17:22:52 -05:00
yhirose 2e124cde02 Enhance documentation and configuration for static site generator
- Update README for clarity and quick start instructions
- Refine default config.toml with hostname and base path
- Adjust index.md files for consistent heading levels
- Simplify CSS for code block styling and remove unnecessary theme switching
- Refactor SiteConfig to derive full base URL from hostname and base path
- Update MarkdownRenderer to remove light theme handling
2026-03-02 00:48:14 -05:00
yhirose fdb589d97e Update dependency 2026-03-01 23:55:52 -05:00
yhirose 843ad379c7 Add search functionality across documentation pages
- Implemented a search button in the header of each documentation page.
- Added a search modal that allows users to input search queries.
- Integrated a JavaScript search feature that fetches and displays results from a new `pages-data.json` file.
- Each documentation page now includes a search overlay for improved navigation.
- Updated the main JavaScript file to handle search logic, including result highlighting and navigation.
- Created a `pages-data.json` file containing metadata for all documentation pages to facilitate search functionality.
2026-03-01 23:37:51 -05:00
yhirose cda9680cdc Update document site 2026-03-01 23:12:45 -05:00
yhirose e906c31a79 Add favicon and update navigation icons across documentation
- Added a favicon link to all tour pages in the Japanese documentation.
- Updated navigation links to include SVG icons for Home and GitHub.
- Changed language button to include an SVG icon for better visual representation.
- Improved theme toggle button to use SVG icons for light and dark modes.
- Refactored the documentation build commands in the justfile for clarity and consistency.
2026-03-01 23:04:38 -05:00
yhirose 2d669c3636 Refactor main function to display help message when no command is provided 2026-03-01 23:04:38 -05:00
yhirose b2d76658fc Add default templates, styles, and scripts for documentation site 2026-03-01 23:04:38 -05:00
Charles von Kalm 7444646627 Removed unused local variable (#2382) 2026-03-01 18:02:57 -05:00
Matheus Gabriel Werny 82a61a6b60 [CMake] New compoments MbedTLS and wolfSSL (#2360)
* [CMake] New component MbedTLS

New component MbedTLS.

* Fix case

Fix case: HTTPLIB_REQUIRE_OPENSSL=OFF; HTTPLIB_REQUIRE_MBEDTLS=ON

* [CMake] Test target MbedTLS::tfpsacrypto

[CMake] Test target MbedTLS::tfpsacrypto.

* [CMake] Test MbedTLS::mbedx509

[CMake] Test MbedTLS::mbedx509.

* Revert "[CMake] Test MbedTLS::mbedx509"

This reverts commit 1d0b91f59a.

* Revert "[CMake] Test target MbedTLS::tfpsacrypto"

This reverts commit bf099f6264.

* Fix problem caused by the recent performance improvement

* wolfSSL support

wolfSSL support.
Partly solve https://github.com/yhirose/cpp-httplib/issues/2371. Only
meson is missing.

* Solve https://github.com/yhirose/cpp-httplib/issues/2361

Solve https://github.com/yhirose/cpp-httplib/issues/2361.
Apply `WARNING`.

* Fix variable

Fix variable.

* [CMake] Solve incompatibilities with loop

Solve incompatibilities with loop.

* Fix

Fix.

* Remove debug prints

Remove debug prints.

* [CMake] Fix bug

Prevent a bug aus the required and if available libraries are checked
independently from each other. A could be chosen in required but B could
be chosen in if available and everything would pass.

* Remove debug print

Remove debug print.

* Restore change

Restore change.

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-03-01 18:00:36 -05:00
yhirose 63ede29db1 Update README 2026-03-01 17:34:03 -05:00
yhirose ae64a5ee90 Fix #2381 2026-02-28 22:07:44 -05:00
yhirose f441fc33fb Update README with documentation link and formatting
Added a line break and a link to the official documentation.
2026-02-28 21:58:58 -05:00
yhirose a9fc935919 Add a link to GitHub 2026-02-28 21:25:01 -05:00
yhirose b6cd71d4ff Update docs/ 2026-02-28 20:58:42 -05:00
yhirose bda599bfb4 Fix base_dir for GitHub PageS 2026-02-28 20:56:46 -05:00
yhirose 797758a742 Documentation Site on GitHub Pages (#2376)
* Add initial documentations

* Update documentation for Basic Client and add WebSocket section

* feat: add a static site generator with multi-language support

- Introduced a new Rust-based static site generator in the `docs-gen` directory.
- Implemented core functionality for building sites from markdown files, including:
  - Configuration loading from `config.toml`.
  - Markdown rendering with frontmatter support.
  - Navigation generation based on page structure.
  - Static file copying and output directory management.
- Added templates for base layout, pages, and portal.
- Created a CSS file for styling and a JavaScript file for interactive features like language selection and theme toggling.
- Updated documentation source with new configuration and example pages in English and Japanese.
- Added a `justfile` target for building the documentation site.

* Add language/theme toggle functionality

- Created a new Japanese tour index page at docs/ja/tour/index.html
- Implemented navigation links for various sections of the cpp-httplib tutorial
- Added a language selector to switch between English and Japanese
- Introduced theme toggle functionality to switch between light and dark modes
- Added mobile sidebar toggle for better navigation on smaller screens
2026-02-28 14:45:40 -05:00
49 changed files with 4747 additions and 457 deletions
+33
View File
@@ -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
+36
View File
@@ -0,0 +1,36 @@
name: 32-bit Build Test
on:
push:
branches: [master]
pull_request:
branches: [master]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref || github.run_id }}
cancel-in-progress: true
jobs:
test-win32:
name: Windows 32-bit (MSVC x86)
runs-on: windows-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- name: Build (Win32)
shell: cmd
run: |
call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86
cl /std:c++14 /EHsc /W4 /WX /c /Fo:NUL test\test_32bit_build.cpp
test-arm32:
name: ARM 32-bit (cross-compile)
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- name: Install cross compiler
run: sudo apt-get update && sudo apt-get install -y g++-arm-linux-gnueabihf
- name: Build (ARM 32-bit)
run: arm-linux-gnueabihf-g++ -std=c++11 -Wall -Wextra -Wno-psabi -Werror -c -o /dev/null test/test_32bit_build.cpp
+3 -7
View File
@@ -40,7 +40,7 @@ jobs:
clang-format --version
cd test && make style_check
build-error-check-on-32bit:
build-and-test-on-32bit:
runs-on: ubuntu-latest
if: >
(github.event_name == 'push') ||
@@ -64,9 +64,8 @@ jobs:
libssl-dev${{ matrix.config.arch_suffix }} libcurl4-openssl-dev${{ matrix.config.arch_suffix }} \
zlib1g-dev${{ matrix.config.arch_suffix }} libbrotli-dev${{ matrix.config.arch_suffix }} \
libzstd-dev${{ matrix.config.arch_suffix }}
- name: build and run tests (expect failure)
- name: build and run tests
run: cd test && make test EXTRA_CXXFLAGS="${{ matrix.config.arch_flags }}"
continue-on-error: true
ubuntu:
runs-on: ubuntu-latest
@@ -229,7 +228,7 @@ jobs:
for ($i = 0; $i -lt $shards; $i++) {
$log = "shard_${i}.log"
$procs += Start-Process -FilePath ./Release/httplib-test.exe `
-ArgumentList "--gtest_color=yes","--gtest_filter=${{ github.event.inputs.gtest_filter || '*' }}-*BenchmarkTest*" `
-ArgumentList "--gtest_color=yes","--gtest_filter=${{ github.event.inputs.gtest_filter || '*' }}" `
-NoNewWindow -PassThru -RedirectStandardOutput $log -RedirectStandardError "${log}.err" `
-Environment @{ GTEST_TOTAL_SHARDS="$shards"; GTEST_SHARD_INDEX="$i" }
}
@@ -249,9 +248,6 @@ jobs:
}
if ($failed) { exit 1 }
Write-Host "All shards passed."
- name: Run benchmark tests with retry ${{ matrix.config.name }}
if: ${{ matrix.config.run_tests }}
run: ctest --output-on-failure --test-dir build -C Release -R "BenchmarkTest" --repeat until-pass:5
env:
VCPKG_ROOT: "C:/vcpkg"
+79
View File
@@ -0,0 +1,79 @@
name: benchmark
on:
push:
pull_request:
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref || github.run_id }}
cancel-in-progress: true
jobs:
ubuntu:
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
steps:
- name: checkout
uses: actions/checkout@v4
- name: build and run
run: cd test && make test_benchmark && ./test_benchmark
macos:
runs-on: macos-latest
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
steps:
- name: checkout
uses: actions/checkout@v4
- name: build and run
run: cd test && make test_benchmark && ./test_benchmark
windows:
runs-on: windows-latest
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
steps:
- name: Prepare Git for Checkout on Windows
run: |
git config --global core.autocrlf false
git config --global core.eol lf
- name: checkout
uses: actions/checkout@v4
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v7
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Cache vcpkg packages
id: vcpkg-cache
uses: actions/cache@v4
with:
path: C:/vcpkg/installed
key: vcpkg-installed-windows-gtest
- name: Install vcpkg dependencies
if: steps.vcpkg-cache.outputs.cache-hit != 'true'
run: vcpkg install gtest
- name: Configure and build
shell: pwsh
run: |
$cmake_content = @"
cmake_minimum_required(VERSION 3.14)
project(httplib-benchmark CXX)
find_package(GTest REQUIRED)
add_executable(httplib-benchmark test/test_benchmark.cc)
target_include_directories(httplib-benchmark PRIVATE .)
target_link_libraries(httplib-benchmark PRIVATE GTest::gtest_main)
target_compile_options(httplib-benchmark PRIVATE "$<$<CXX_COMPILER_ID:MSVC>:/utf-8>")
"@
New-Item -ItemType Directory -Force -Path build_bench/test | Out-Null
Set-Content -Path build_bench/CMakeLists.txt -Value $cmake_content
Copy-Item -Path httplib.h -Destination build_bench/
Copy-Item -Path test/test_benchmark.cc -Destination build_bench/test/
cmake -B build_bench/build -S build_bench `
-DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake"
cmake --build build_bench/build --config Release
- name: Run with retry
run: ctest --output-on-failure --test-dir build_bench/build -C Release --repeat until-pass:5
env:
VCPKG_ROOT: "C:/vcpkg"
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
+5 -1
View File
@@ -28,6 +28,10 @@ jobs:
- name: Run proxy tests (OpenSSL)
if: matrix.tls_backend == 'openssl'
run: cd test && make proxy
env:
COMPOSE_FILE: docker-compose.yml:docker-compose.ci.yml
- name: Run proxy tests (Mbed TLS)
if: matrix.tls_backend == 'mbedtls'
run: cd test && make proxy_mbedtls
run: cd test && make proxy_mbedtls
env:
COMPOSE_FILE: docker-compose.yml:docker-compose.ci.yml
+5
View File
@@ -1,4 +1,7 @@
tags
AGENTS.md
docs-src/pages/AGENTS.md
plans/
# Ignore executables (no extension) but not source files
example/server
@@ -48,6 +51,7 @@ test/test_split_wolfssl
test/test_split_no_tls
test/test_websocket_heartbeat
test/test_thread_pool
test/test_benchmark
test/test.xcodeproj/xcuser*
test/test.xcodeproj/*/xcuser*
test/*.o
@@ -57,6 +61,7 @@ test/*.log
test/_build_*
work/
benchmark/server*
docs-gen/target/
*.swp
+49 -5
View File
@@ -2,11 +2,15 @@
Build options:
* Standard BUILD_SHARED_LIBS is supported and sets HTTPLIB_SHARED default value.
* HTTPLIB_USE_OPENSSL_IF_AVAILABLE (default on)
* HTTPLIB_USE_WOLFSSL_IF_AVAILABLE (default off)
* HTTPLIB_USE_MBEDTLS_IF_AVAILABLE (default off)
* HTTPLIB_USE_ZLIB_IF_AVAILABLE (default on)
* HTTPLIB_USE_BROTLI_IF_AVAILABLE (default on)
* HTTPLIB_USE_ZSTD_IF_AVAILABLE (default on)
* HTTPLIB_BUILD_MODULES (default off)
* HTTPLIB_REQUIRE_OPENSSL (default off)
* HTTPLIB_REQUIRE_WOLFSSL (default off)
* HTTPLIB_REQUIRE_MBEDTLS (default off)
* HTTPLIB_REQUIRE_ZLIB (default off)
* HTTPLIB_REQUIRE_BROTLI (default off)
* HTTPLIB_REQUIRE_ZSTD (default off)
@@ -21,7 +25,7 @@
-------------------------------------------------------------------------------
After installation with Cmake, a find_package(httplib COMPONENTS OpenSSL ZLIB Brotli zstd) is available.
After installation with Cmake, a find_package(httplib COMPONENTS OpenSSL wolfssl MbedTLS ZLIB Brotli zstd) is available.
This creates a httplib::httplib target (if found and if listed components are supported).
It can be linked like so:
@@ -48,6 +52,8 @@
These variables are available after you run find_package(httplib)
* HTTPLIB_HEADER_PATH - this is the full path to the installed header (e.g. /usr/include/httplib.h).
* HTTPLIB_IS_USING_OPENSSL - a bool for if OpenSSL support is enabled.
* HTTPLIB_IS_USING_WOLFSSL - a bool for if wolfSSL support is enabled.
* HTTPLIB_IS_USING_MBEDTLS - a bool for if MbedTLS support is enabled.
* HTTPLIB_IS_USING_ZLIB - a bool for if ZLIB support is enabled.
* HTTPLIB_IS_USING_BROTLI - a bool for if Brotli support is enabled.
* HTTPLIB_IS_USING_ZSTD - a bool for if ZSTD support is enabled.
@@ -95,10 +101,14 @@ set(_HTTPLIB_OPENSSL_MIN_VER "3.0.0")
option(HTTPLIB_NO_EXCEPTIONS "Disable the use of C++ exceptions" OFF)
# Allow for a build to require OpenSSL to pass, instead of just being optional
option(HTTPLIB_REQUIRE_OPENSSL "Requires OpenSSL to be found & linked, or fails build." OFF)
option(HTTPLIB_REQUIRE_WOLFSSL "Requires wolfSSL to be found & linked, or fails build." OFF)
option(HTTPLIB_REQUIRE_MBEDTLS "Requires MbedTLS to be found & linked, or fails build." OFF)
option(HTTPLIB_REQUIRE_ZLIB "Requires ZLIB to be found & linked, or fails build." OFF)
# Allow for a build to casually enable OpenSSL/ZLIB support, but silently continue if not found.
# Make these options so their automatic use can be specifically disabled (as needed)
option(HTTPLIB_USE_OPENSSL_IF_AVAILABLE "Uses OpenSSL (if available) to enable HTTPS support." ON)
option(HTTPLIB_USE_WOLFSSL_IF_AVAILABLE "Uses wolfSSL (if available) to enable HTTPS support." OFF)
option(HTTPLIB_USE_MBEDTLS_IF_AVAILABLE "Uses MbedTLS (if available) to enable HTTPS support." OFF)
option(HTTPLIB_USE_ZLIB_IF_AVAILABLE "Uses ZLIB (if available) to enable Zlib compression support." ON)
# Lets you compile the program as a regular library instead of header-only
option(HTTPLIB_COMPILE "If ON, uses a Python script to split the header into a compilable header & source file (requires Python v3)." OFF)
@@ -120,6 +130,23 @@ else()
message(WARNING "HTTPLIB_BUILD_MODULES requires CMake 3.28 or later. Current version is ${CMAKE_VERSION}. Modules support has been disabled.")
endif()
endif()
# Incompatibility between TLS libraries
set(TLS_LIBRARIES_USED_TMP 0)
foreach(tls_library OPENSSL WOLFSSL MBEDTLS)
set(TLS_REQUIRED ${HTTPLIB_REQUIRE_${tls_library}})
set(TLS_IF_AVAILABLE ${HTTPLIB_USE_${tls_library}_IF_AVAILABLE})
if(TLS_REQUIRED OR TLS_IF_AVAILABLE)
math(EXPR TLS_LIBRARIES_USED_TMP "${TLS_LIBRARIES_USED_TMP} + 1")
endif()
endforeach()
if(TLS_LIBRARIES_USED_TMP GREATER 1)
message(FATAL_ERROR "TLS libraries are mutually exclusive.")
endif()
# Defaults to static library but respects standard BUILD_SHARED_LIBS if set
include(CMakeDependentOption)
cmake_dependent_option(HTTPLIB_SHARED "Build the library as a shared library instead of static. Has no effect if using header-only."
@@ -139,16 +166,13 @@ endif()
if(CMAKE_SYSTEM_NAME MATCHES "Windows")
if(CMAKE_SYSTEM_VERSION)
if(${CMAKE_SYSTEM_VERSION} VERSION_LESS "10.0.0")
message(SEND_ERROR "Windows ${CMAKE_SYSTEM_VERSION} or lower is not supported. Please use Windows 10 or later.")
message(WARNING "Windows ${CMAKE_SYSTEM_VERSION} or lower is not supported. Please use Windows 10 or later.")
endif()
else()
set(CMAKE_SYSTEM_VERSION "10.0.19041.0")
message(WARNING "The target is Windows but CMAKE_SYSTEM_VERSION is not set, the default system version is set to Windows 10.")
endif()
endif()
if(CMAKE_SIZEOF_VOID_P LESS 8)
message(WARNING "Pointer size ${CMAKE_SIZEOF_VOID_P} is not supported. Please use a 64-bit compiler.")
endif()
# Set some variables that are used in-tree and while building based on our options
set(HTTPLIB_IS_COMPILED ${HTTPLIB_COMPILE})
@@ -176,6 +200,22 @@ elseif(HTTPLIB_USE_OPENSSL_IF_AVAILABLE)
endif()
endif()
if(HTTPLIB_REQUIRE_WOLFSSL)
find_package(wolfssl REQUIRED)
set(HTTPLIB_IS_USING_WOLFSSL TRUE)
elseif(HTTPLIB_USE_WOLFSSL_IF_AVAILABLE)
find_package(wolfssl QUIET)
set(HTTPLIB_IS_USING_WOLFSSL ${wolfssl_FOUND})
endif()
if(HTTPLIB_REQUIRE_MBEDTLS)
find_package(MbedTLS REQUIRED)
set(HTTPLIB_IS_USING_MBEDTLS TRUE)
elseif(HTTPLIB_USE_MBEDTLS_IF_AVAILABLE)
find_package(MbedTLS QUIET)
set(HTTPLIB_IS_USING_MBEDTLS ${MbedTLS_FOUND})
endif()
if(HTTPLIB_REQUIRE_ZLIB)
find_package(ZLIB REQUIRED)
set(HTTPLIB_IS_USING_ZLIB TRUE)
@@ -330,6 +370,8 @@ target_link_libraries(${PROJECT_NAME} ${_INTERFACE_OR_PUBLIC}
$<$<BOOL:${HTTPLIB_IS_USING_ZSTD}>:zstd::libzstd>
$<$<BOOL:${HTTPLIB_IS_USING_OPENSSL}>:OpenSSL::SSL>
$<$<BOOL:${HTTPLIB_IS_USING_OPENSSL}>:OpenSSL::Crypto>
$<$<BOOL:${HTTPLIB_IS_USING_WOLFSSL}>:wolfssl::wolfssl>
$<$<BOOL:${HTTPLIB_IS_USING_MBEDTLS}>:MbedTLS::mbedtls>
)
# Set the definitions to enable optional features
@@ -339,6 +381,8 @@ target_compile_definitions(${PROJECT_NAME} ${_INTERFACE_OR_PUBLIC}
$<$<BOOL:${HTTPLIB_IS_USING_ZLIB}>:CPPHTTPLIB_ZLIB_SUPPORT>
$<$<BOOL:${HTTPLIB_IS_USING_ZSTD}>:CPPHTTPLIB_ZSTD_SUPPORT>
$<$<BOOL:${HTTPLIB_IS_USING_OPENSSL}>:CPPHTTPLIB_OPENSSL_SUPPORT>
$<$<BOOL:${HTTPLIB_IS_USING_WOLFSSL}>:CPPHTTPLIB_WOLFSSL_SUPPORT>
$<$<BOOL:${HTTPLIB_IS_USING_MBEDTLS}>:CPPHTTPLIB_MBEDTLS_SUPPORT>
$<$<AND:$<PLATFORM_ID:Darwin>,$<BOOL:${HTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES}>>:CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES>
$<$<BOOL:${HTTPLIB_USE_NON_BLOCKING_GETADDRINFO}>:CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO>
)
+2 -2
View File
@@ -45,7 +45,7 @@ cpp-httplib provides multiple API layers for different use cases:
```text
┌─────────────────────────────────────────────┐
│ SSEClient (planned) │ ← SSE-specific, parsed events
│ SSEClient │ ← SSE-specific, parsed events
│ - on_message(), on_event() │
│ - Auto-reconnect, Last-Event-ID │
├─────────────────────────────────────────────┤
@@ -61,7 +61,7 @@ cpp-httplib provides multiple API layers for different use cases:
| Use Case | Recommended API |
|----------|----------------|
| SSE with auto-reconnect | SSEClient (planned) or `ssecli-stream.cc` example |
| SSE with auto-reconnect | `SSEClient` (see [README-sse.md](README-sse.md)) |
| LLM streaming (JSON Lines) | `stream::Get()` |
| Large file download | `stream::Get()` or `open_stream()` |
| Reverse proxy | `open_stream()` |
+20
View File
@@ -353,6 +353,26 @@ if (ws.connect()) {
| `CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND` | `5` | Timeout for waiting peer's Close response (seconds) |
| `CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND` | `30` | Automatic Ping interval for heartbeat (seconds) |
### Runtime Ping Interval
You can override the ping interval at runtime instead of changing the compile-time macro. Set it to `0` to disable automatic pings entirely.
```cpp
// Server side
httplib::Server svr;
svr.set_websocket_ping_interval(10); // 10 seconds
// Or using std::chrono
svr.set_websocket_ping_interval(std::chrono::seconds(10));
// Client side
httplib::ws::WebSocketClient ws("ws://localhost:8080/ws");
ws.set_websocket_ping_interval(10); // 10 seconds
// Disable automatic pings
ws.set_websocket_ping_interval(0);
```
## Threading Model
WebSocket connections share the same thread pool as HTTP requests. Each WebSocket connection occupies one thread for its entire lifetime.
+44 -34
View File
@@ -2,13 +2,17 @@
[![](https://github.com/yhirose/cpp-httplib/workflows/test/badge.svg)](https://github.com/yhirose/cpp-httplib/actions)
A C++11 single-file header-only cross platform HTTP/HTTPS library.
A C++11 single-file header-only cross platform HTTP/HTTPS library.<br>
It's extremely easy to set up. Just include the **[httplib.h](https://raw.githubusercontent.com/yhirose/cpp-httplib/refs/heads/master/httplib.h)** file in your code!
It's extremely easy to set up. Just include the **httplib.h** file in your code!
Learn more in the [official documentation](https://yhirose.github.io/cpp-httplib/) (built with [docs-gen](https://github.com/yhirose/docs-gen)).
> [!IMPORTANT]
> This library uses 'blocking' socket I/O. If you are looking for a library with 'non-blocking' socket I/O, this is not the one that you want.
> [!WARNING]
> 32-bit platforms are **NOT supported**. Use at your own risk. The library may compile on 32-bit targets, but no security review has been conducted for 32-bit environments. Integer truncation and other 32-bit-specific issues may exist. **Security reports that only affect 32-bit platforms will be closed without action.** The maintainer does not have access to 32-bit environments for testing or fixing issues. CI includes basic compile checks only, not functional or security testing.
## Main Features
- HTTP Server/Client
@@ -60,26 +64,14 @@ if (auto res = cli.Get("/hi")) {
cpp-httplib supports multiple TLS backends through an abstraction layer:
| Backend | Define | Libraries |
| :------ | :----- | :-------- |
| OpenSSL | `CPPHTTPLIB_OPENSSL_SUPPORT` | `libssl`, `libcrypto` |
| Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` |
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` |
| Backend | Define | Libraries | Notes |
| :------ | :----- | :-------- | :---- |
| OpenSSL | `CPPHTTPLIB_OPENSSL_SUPPORT` | `libssl`, `libcrypto` | [3.0 or later](https://www.openssl.org/policies/releasestrat.html) required |
| Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` | 2.x and 3.x supported (auto-detected) |
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` |
> [!NOTE]
> OpenSSL 3.0 or later is required. Please see [this page](https://www.openssl.org/policies/releasestrat.html) for more information.
> [!NOTE]
> Mbed TLS 2.x and 3.x are supported. The library automatically detects the version and uses the appropriate API.
> [!NOTE]
> wolfSSL must be built with OpenSSL compatibility layer enabled (`--enable-opensslall`). wolfSSL 5.x is supported.
> [!NOTE]
> **Mbed TLS / wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()` or `load_ca_cert_store(pem, size)`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable with these backends.
> [!TIP]
> For macOS: cpp-httplib automatically loads system certs from the Keychain when a TLS backend is enabled. `CoreFoundation` and `Security` must be linked with `-framework`. To disable this, define `CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES`.
> **Mbed TLS / wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
```c++
// Use either OpenSSL, Mbed TLS, or wolfSSL
@@ -193,27 +185,21 @@ svr.Get("/", [](const httplib::Request &req, httplib::Response &res) {
});
```
### Windows Certificate Verification
### Platform-specific Certificate Handling
On Windows, cpp-httplib automatically performs additional certificate verification using the Windows certificate store via CryptoAPI (`CertGetCertificateChain` / `CertVerifyCertificateChainPolicy`). This works with all TLS backends (OpenSSL, Mbed TLS, and wolfSSL), providing:
cpp-httplib automatically integrates with the OS certificate store on macOS and Windows. This works with all TLS backends.
- Real-time certificate validation integrated with Windows Update
- Certificate revocation checking
- SSL/TLS policy verification using the system certificate store (ROOT and CA)
| Platform | Behavior | Disable (compile time) |
| :------- | :------- | :--------------------- |
| macOS | Loads system certs from Keychain (link `CoreFoundation` and `Security` with `-framework`) | `CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES` |
| Windows | Verifies certs via CryptoAPI (`CertGetCertificateChain` / `CertVerifyCertificateChainPolicy`) with revocation checking | `CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE` |
This feature is enabled by default and can be controlled at runtime:
On Windows, verification can also be disabled at runtime:
```c++
// Disable Windows certificate verification (use only OpenSSL/Mbed TLS/wolfSSL verification)
cli.enable_windows_certificate_verification(false);
```
To disable this feature at compile time, define:
```c++
#define CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
```
> [!NOTE]
> When using SSL, it seems impossible to avoid SIGPIPE in all cases, since on some operating systems, SIGPIPE can only be suppressed on a per-message basis, but there is no way to make the OpenSSL library do so for its internal communications. If your program needs to avoid being terminated on SIGPIPE, the only fully general way might be to set up a signal handler for SIGPIPE to handle or ignore it yourself.
@@ -346,6 +332,11 @@ The following are built-in mappings:
> [!WARNING]
> These static file server methods are not thread-safe.
<!-- -->
> [!NOTE]
> On POSIX systems, the static file server rejects requests that resolve (via symlinks) to a path outside the mounted base directory. Ensure that the served directory has appropriate permissions, as managing access to the served directory is the application developer's responsibility.
### File request handler
```cpp
@@ -536,8 +527,17 @@ svr.Post("/multipart", [&](const Request& req, Response& res) {
std::cout << "Header: " << header.first << " = " << header.second << std::endl;
}
// IMPORTANT: file.filename is an untrusted value from the client.
// Always sanitize to prevent path traversal attacks.
auto safe_name = httplib::sanitize_filename(file.filename);
if (safe_name.empty()) {
res.status = StatusCode::BadRequest_400;
res.set_content("Invalid filename", "text/plain");
return;
}
// Save to disk
std::ofstream ofs(file.filename, std::ios::binary);
std::ofstream ofs(upload_dir + "/" + safe_name, std::ios::binary);
ofs << file.content;
}
@@ -573,6 +573,16 @@ svr.Post("/multipart", [&](const Request& req, Response& res) {
});
```
#### Filename Sanitization
`file.filename` in multipart uploads is an untrusted value from the client. Always sanitize before using it in file paths:
```cpp
auto safe = httplib::sanitize_filename(file.filename);
```
This function strips path separators (`/`, `\`), null bytes, leading/trailing whitespace, and rejects `.` and `..`. Returns an empty string if the filename is unsafe.
### Receive content with a content receiver
```cpp
+13
View File
@@ -4,6 +4,8 @@
# Setting these here so they're accessible after install.
# Might be useful for some users to check which settings were used.
set(HTTPLIB_IS_USING_OPENSSL @HTTPLIB_IS_USING_OPENSSL@)
set(HTTPLIB_IS_USING_WOLFSSL @HTTPLIB_IS_USING_WOLFSSL@)
set(HTTPLIB_IS_USING_MBEDTLS @HTTPLIB_IS_USING_MBEDTLS@)
set(HTTPLIB_IS_USING_ZLIB @HTTPLIB_IS_USING_ZLIB@)
set(HTTPLIB_IS_COMPILED @HTTPLIB_COMPILE@)
set(HTTPLIB_IS_USING_BROTLI @HTTPLIB_IS_USING_BROTLI@)
@@ -25,11 +27,22 @@ if(@HTTPLIB_IS_USING_OPENSSL@)
endif()
set(httplib_OpenSSL_FOUND ${OpenSSL_FOUND})
endif()
if(@HTTPLIB_IS_USING_ZLIB@)
find_dependency(ZLIB)
set(httplib_ZLIB_FOUND ${ZLIB_FOUND})
endif()
if(@HTTPLIB_IS_USING_WOLFSSL@)
find_dependency(wolfssl)
set(httplib_wolfssl_FOUND ${wolfssl_FOUND})
endif()
if(@HTTPLIB_IS_USING_MBEDTLS@)
find_dependency(MbedTLS)
set(httplib_MbedTLS_FOUND ${MbedTLS_FOUND})
endif()
if(@HTTPLIB_IS_USING_BROTLI@)
# Needed so we can use our own FindBrotli.cmake in this file.
# Note that the FindBrotli.cmake file is installed in the same dir as this file.
+30
View File
@@ -0,0 +1,30 @@
[system]
theme = "monotone"
langs = ["en", "ja"]
[site]
title = "cpp-httplib"
version = "0.38.0"
hostname = "https://yhirose.github.io"
base_path = "/cpp-httplib"
footer_message = "© 2026 Yuji Hirose. All rights reserved."
[[nav]]
label = "Tour"
path = "tour/"
icon_svg = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76"/></svg>'
[[nav]]
label = "Cookbook"
path = "cookbook/"
icon_svg = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>'
[[nav]]
label = "LLM App"
path = "llm-app/"
icon_svg = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>'
[[nav]]
label = "GitHub"
url = "https://github.com/yhirose/cpp-httplib"
icon_svg = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/></svg>'
+95
View File
@@ -0,0 +1,95 @@
---
title: "Cookbook"
order: 0
---
A collection of recipes that answer "How do I...?" questions. Each recipe is self-contained — read only what you need.
## Client
### Basics
- Get the response body as a string / save to a file
- Send and receive JSON
- Set default headers (`set_default_headers`)
- Follow redirects (`set_follow_location`)
### Authentication
- Use Basic authentication (`set_basic_auth`)
- Call an API with a Bearer token
### File Upload
- Upload a file as multipart form data (`make_file_provider`)
- POST a file as raw binary (`make_file_body`)
- Send the body with chunked transfer (Content Provider)
### Streaming & Progress
- Receive a response as a stream
- Use the progress callback (`DownloadProgress` / `UploadProgress`)
### Connection & Performance
- Set timeouts (`set_connection_timeout` / `set_read_timeout`)
- Set an overall timeout (`set_max_timeout`)
- Understand connection reuse and Keep-Alive behavior
- Enable compression (`set_compress` / `set_decompress`)
- Send requests through a proxy (`set_proxy`)
### Error Handling & Debugging
- Handle error codes (`Result::error()`)
- Handle SSL errors (`ssl_error()` / `ssl_backend_error()`)
- Set up client logging (`set_logger` / `set_error_logger`)
## Server
### Basics
- Register GET / POST / PUT / DELETE handlers
- Receive JSON requests and return JSON responses
- Use path parameters (`/users/:id`)
- Set up a static file server (`set_mount_point`)
### Streaming & Files
- Stream a large file in the response (`ContentProvider`)
- Return a file download response (`Content-Disposition`)
- Receive multipart data as a stream (`ContentReader`)
- Compress responses (gzip)
### Handler Chain
- Add pre-processing to all routes (Pre-routing handler)
- Add response headers with a Post-routing handler (CORS, etc.)
- Authenticate per route with a Pre-request handler (`matched_route`)
- Pass data between handlers with `res.user_data`
### Error Handling & Debugging
- Return custom error pages (`set_error_handler`)
- Catch exceptions (`set_exception_handler`)
- Log requests (Logger)
- Detect client disconnection (`req.is_connection_closed()`)
### Operations & Tuning
- Assign a port dynamically (`bind_to_any_port`)
- Control startup order with `listen_after_bind`
- Shut down gracefully (`stop()` and signal handling)
- Tune Keep-Alive (`set_keep_alive_max_count` / `set_keep_alive_timeout`)
- Configure the thread pool (`new_task_queue`)
## TLS / Security
- Choosing between OpenSSL, mbedTLS, and wolfSSL (build-time `#define` differences)
- Control SSL certificate verification (disable, custom CA, custom callback)
- Use a custom certificate verification callback (`set_server_certificate_verifier`)
- Set up an SSL/TLS server (certificate and private key)
- Configure mTLS (mutual TLS with client certificates)
- Access the peer certificate on the server (`req.peer_cert()` / SNI)
## SSE
- Implement an SSE server
- Use event names to distinguish event types
- Handle reconnection (`Last-Event-ID`)
- Receive SSE events on the client
## WebSocket
- Implement a WebSocket echo server and client
- Configure heartbeats (`set_websocket_ping_interval` / `CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND`)
- Handle connection close
- Send and receive binary frames
+22
View File
@@ -0,0 +1,22 @@
---
title: "cpp-httplib"
order: 0
---
[cpp-httplib](https://github.com/yhirose/cpp-httplib) is an HTTP/HTTPS library for C++. Just copy a single header file, [`httplib.h`](https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/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](tour/) — A step-by-step tutorial covering the basics. Start here if you're new
- [Cookbook](cookbook/) — A collection of recipes organized by topic. Jump to whatever you need
- [Building a Desktop LLM App](llm-app/) — A hands-on guide to building a desktop app with llama.cpp, step by step
+22
View File
@@ -0,0 +1,22 @@
---
title: "Building a Desktop LLM App with cpp-httplib"
order: 0
---
Build an LLM-powered translation desktop app step by step, learning both the server and client sides of cpp-httplib along the way. Translation is just an example — swap it out to build your own summarizer, code generator, chatbot, or any other LLM application.
## Dependencies
- [llama.cpp](https://github.com/ggml-org/llama.cpp) — LLM inference engine
- [nlohmann/json](https://github.com/nlohmann/json) — JSON parser (header-only)
- [webview/webview](https://github.com/webview/webview) — WebView wrapper (header-only)
- [cpp-httplib](https://github.com/yhirose/cpp-httplib) — HTTP server/client (header-only)
## Chapters
1. **Embed llama.cpp and create a REST API** — Start with a simple API that accepts text via POST and returns a translation as JSON
2. **Add token streaming with SSE** — Stream translation results token by token using the standard LLM API approach
3. **Add model discovery and download** — Use the client to search and download GGUF models from Hugging Face
4. **Add a Web UI** — Serve a translation UI with static file hosting, making the app accessible from a browser
5. **Turn it into a desktop app with WebView** — Wrap the web app with webview/webview to create an Electron-like desktop application
6. **Code reading: llama.cpp's server implementation** — Compare your implementation with production-quality code and learn from the differences
@@ -0,0 +1,88 @@
---
title: "Getting Started"
order: 1
---
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.
```sh
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-select --install`) |
| Ubuntu | clang++ or g++ | `apt install clang` or `apt install g++` |
| Windows | MSVC | Visual Studio 2022 or later (install with C++ components) |
## Hello World Server
Save the following code as `server.cpp`.
```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);
}
```
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.
```sh
# 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.
```sh
# 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`.
```sh
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](../02-basic-client)
+266
View File
@@ -0,0 +1,266 @@
---
title: "Basic Client"
order: 2
---
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.
```cpp
#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.
```cpp
#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.
```sh
curl http://localhost:8080/hi
# Hello!
```
## Checking the Response
A response contains header information in addition to the status code and body.
```cpp
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](https://github.com/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`.
```cpp
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.
```sh
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.
```cpp
auto res = cli.Get("/users/42");
if (res) {
std::cout << res->body << std::endl; // User ID: 42
}
```
```sh
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.
```cpp
auto res = cli.Get("/files/42");
if (res) {
std::cout << res->body << std::endl; // File ID: 42
}
```
```sh
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()`.
```cpp
auto res = cli.Get("/hi", httplib::Headers{
{"Authorization", "Bearer my-token"}
});
```
```sh
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.
```cpp
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.
```sh
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.
```cpp
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.
```sh
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.
```cpp
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}`.
```sh
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.
```cpp
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](../03-basic-server)
+280
View File
@@ -0,0 +1,280 @@
---
title: "Basic Server"
order: 3
---
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.
```cpp
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.
```cpp
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.
```cpp
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.
```cpp
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`.
```cpp
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.
```cpp
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.
```cpp
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`.
```cpp
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()`.
```cpp
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.
```cpp
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.
```cpp
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`.
```cpp
// 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.
```cpp
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`.
```cpp
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()`.
```cpp
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
```cpp
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
```cpp
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
```cpp
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
```cpp
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
```cpp
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
```cpp
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+)
```cpp
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](../04-static-file-server)
@@ -0,0 +1,134 @@
---
title: "Static File Server"
order: 4
---
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.
```cpp
#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.
```sh
mkdir html
```
```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.
```sh
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`.
```cpp
httplib::Client cli("http://localhost:8080");
auto res = cli.Get("/");
if (res) {
std::cout << res->body << std::endl; // HTML is displayed
}
```
```sh
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.
```cpp
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.
```cpp
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.
```cpp
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.
```sh
> 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](../05-tls-setup)
+88
View File
@@ -0,0 +1,88 @@
---
title: "TLS Setup"
order: 5
---
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](https://brew.sh/) (`brew install openssl`) |
| Ubuntu / Debian | `sudo apt install libssl-dev` |
| Windows | [vcpkg](https://vcpkg.io/) (`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.
```sh
# 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`.
```cpp
#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.
| Backend | Macro | Libraries to link |
| :--- | :--- | :--- |
| OpenSSL | `CPPHTTPLIB_OPENSSL_SUPPORT` | `libssl`, `libcrypto` |
| Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` |
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` |
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](../06-https-client)
+122
View File
@@ -0,0 +1,122 @@
---
title: "HTTPS Client"
order: 6
---
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.
```cpp
#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.
```sh
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.
```cpp
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.
```cpp
httplib::Client cli("https://nghttp2.org");
cli.set_ca_cert_path("/etc/ssl/certs/ca-certificates.crt");
auto res = cli.Get("/");
```
```sh
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.
```cpp
httplib::Client cli("https://localhost:8443");
cli.enable_server_certificate_verification(false);
auto res = cli.Get("/");
```
```sh
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.
```cpp
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;
}
```
```sh
curl https://nghttp2.org/httpbin/redirect/3
```
Call `set_follow_location(true)` to automatically follow redirects and get the final response.
```cpp
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)
}
```
```sh
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](../07-https-server)
+124
View File
@@ -0,0 +1,124 @@
---
title: "HTTPS Server"
order: 7
---
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.
```sh
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.
```cpp
#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.
```sh
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.
```cpp
#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.
```cpp
#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::Server` | `httplib::SSLServer` |
| -- | ------------------ | -------------------- |
| Constructor | No arguments | Certificate and private key paths |
| Protocol | HTTP | HTTPS |
| Port (convention) | 8080 | 8443 |
| Routing | Same | Same |
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](../08-websocket)
+139
View File
@@ -0,0 +1,139 @@
---
title: "WebSocket"
order: 8
---
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.
```cpp
#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`.
```cpp
#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()`.
```cpp
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.
```cpp
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`.
```cpp
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.
```cpp
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](../09-whats-next)
+228
View File
@@ -0,0 +1,228 @@
---
title: "What's Next"
order: 9
---
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.
```cpp
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.
```cpp
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.
```cpp
// 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.
```cpp
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`.
```cpp
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.
```cpp
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.
```cpp
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.
| Method | Macro |
| -- | -- |
| gzip | `CPPHTTPLIB_ZLIB_SUPPORT` |
| Brotli | `CPPHTTPLIB_BROTLI_SUPPORT` |
| Zstandard | `CPPHTTPLIB_ZSTD_SUPPORT` |
```cpp
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.
```cpp
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.
```cpp
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.
```cpp
httplib::Client cli("https://example.com");
cli.set_keep_alive(true);
```
## Server Middleware
You can hook into request processing before and after handlers run.
```cpp
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 `res.user_data` to pass data from middleware to handlers. This is useful for sharing things like decoded auth tokens.
```cpp
svr.set_pre_routing_handler([](const auto &req, auto &res) {
res.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>(res.user_data.at("auth_user"));
res.set_content("Hello, " + user, "text/plain");
});
```
You can also customize error and exception handlers.
```cpp
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.
```cpp
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.
```cpp
// Server
httplib::Server svr;
svr.set_address_family(AF_UNIX);
svr.listen("/tmp/httplib.sock", 0);
```
```cpp
// 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](https://github.com/yhirose/cpp-httplib/blob/master/README.md) — Full API reference
- [README-sse](https://github.com/yhirose/cpp-httplib/blob/master/README-sse.md) — How to use Server-Sent Events
- [README-stream](https://github.com/yhirose/cpp-httplib/blob/master/README-stream.md) — How to use the Streaming API
- [README-websocket](https://github.com/yhirose/cpp-httplib/blob/master/README-websocket.md) — How to use the WebSocket server
+16
View File
@@ -0,0 +1,16 @@
---
title: "A Tour of cpp-httplib"
order: 0
---
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](01-getting-started) — Get httplib.h and build a Hello World server
2. [Basic Client](02-basic-client) — Send GET/POST requests and use path parameters
3. [Basic Server](03-basic-server) — Routing, path parameters, and building responses
4. [Static File Server](04-static-file-server) — Serve static files
5. [TLS Setup](05-tls-setup) — Set up OpenSSL / mbedTLS
6. [HTTPS Client](06-https-client) — Make requests to HTTPS sites
7. [HTTPS Server](07-https-server) — Build an HTTPS server
8. [WebSocket](08-websocket) — Learn the basics of WebSocket communication
9. [What's Next](09-whats-next) — Explore more features
+95
View File
@@ -0,0 +1,95 @@
---
title: "Cookbook"
order: 0
---
「〇〇をするには?」という問いに答えるレシピ集です。各レシピは独立しているので、必要なページだけ読めます。
## クライアント
### 基本
- レスポンスボディを文字列で取得する / ファイルに保存する
- JSON を送受信する
- デフォルトヘッダーを設定する(`set_default_headers`
- リダイレクトを追従する(`set_follow_location`
### 認証
- Basic 認証を使う(`set_basic_auth`
- Bearer トークンで API を呼ぶ
### ファイル送信
- ファイルをマルチパートフォームとしてアップロードする(`make_file_provider`
- ファイルを生バイナリとして POST する(`make_file_body`
- チャンク転送でボディを送る(Content Provider
### ストリーミング・進捗
- レスポンスをストリーミングで受信する
- 進捗コールバックを使う(`DownloadProgress` / `UploadProgress`
### 接続・パフォーマンス
- タイムアウトを設定する(`set_connection_timeout` / `set_read_timeout`
- 全体タイムアウトを設定する(`set_max_timeout`
- 接続の再利用と Keep-Alive の挙動を理解する
- 圧縮を有効にする(`set_compress` / `set_decompress`
- プロキシを経由してリクエストを送る(`set_proxy`
### エラー処理・デバッグ
- エラーコードをハンドリングする(`Result::error()`
- SSL エラーをハンドリングする(`ssl_error()` / `ssl_backend_error()`
- クライアントにログを設定する(`set_logger` / `set_error_logger`
## サーバー
### 基本
- GET / POST / PUT / DELETE ハンドラを登録する
- JSON リクエストを受け取り JSON レスポンスを返す
- パスパラメーターを使う(`/users/:id`
- 静的ファイルサーバーを設定する(`set_mount_point`
### ストリーミング・ファイル
- 大きなファイルをストリーミングで返す(`ContentProvider`
- ファイルダウンロードレスポンスを返す(`Content-Disposition`
- マルチパートデータをストリーミングで受け取る(`ContentReader`
- レスポンスを圧縮して返す(gzip)
### ハンドラチェーン
- 全ルートに共通の前処理をする(Pre-routing handler
- Post-routing handler でレスポンスヘッダーを追加する(CORS など)
- Pre-request handler でルート単位の認証を行う(`matched_route`
- `res.user_data` でハンドラ間データを渡す
### エラー処理・デバッグ
- カスタムエラーページを返す(`set_error_handler`
- 例外をキャッチする(`set_exception_handler`
- リクエストをログに記録する(Logger)
- クライアントが切断したか検出する(`req.is_connection_closed()`
### 運用・チューニング
- ポートを動的に割り当てる(`bind_to_any_port`
- `listen_after_bind` で起動順序を制御する
- グレースフルシャットダウンする(`stop()` とシグナルハンドリング)
- Keep-Alive を調整する(`set_keep_alive_max_count` / `set_keep_alive_timeout`
- マルチスレッド数を設定する(`new_task_queue`
## TLS / セキュリティ
- OpenSSL・mbedTLS・wolfSSL の選択指針(ビルド時の `#define` の違い)
- SSL 証明書の検証を制御する(証明書の無効化・カスタム CA・カスタムコールバック)
- カスタム証明書検証コールバックを使う(`set_server_certificate_verifier`
- SSL/TLS サーバーを立ち上げる(証明書・秘密鍵の設定)
- mTLS(クライアント証明書による相互認証)を設定する
- サーバー側でピア証明書を参照する(`req.peer_cert()` / SNI
## SSE
- SSE サーバーを実装する
- SSE でイベント名を使い分ける
- SSE の再接続を処理する(`Last-Event-ID`
- SSE をクライアントで受信する
## WebSocket
- WebSocket エコーサーバー/クライアントを実装する
- ハートビートを設定する(`set_websocket_ping_interval` / `CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND`
- 接続クローズをハンドリングする
- バイナリフレームを送受信する
+22
View File
@@ -0,0 +1,22 @@
---
title: "cpp-httplib"
order: 0
---
[cpp-httplib](https://github.com/yhirose/cpp-httplib)は、C++用のHTTP/HTTPSライブラリです。[`httplib.h`](https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h) というヘッダーファイルを1枚コピーするだけで使えます。
C++でちょっとしたHTTPサーバーやクライアントが必要になったとき、すぐに動くものが欲しいですよね。cpp-httplibはまさにそのために作られました。サーバーもクライアントも、数行のコードで書き始められます。
APIはラムダ式をベースにした直感的な設計で、C++11以降のコンパイラーがあればどこでも動きます。Windows、macOS、Linux — お使いの環境をそのまま使えます。
HTTPSも使えます。OpenSSLやmbedTLSをリンクするだけで、サーバー・クライアントの両方がTLSに対応します。Content-Encodinggzip, brotli等)、ファイルアップロードなど、実際の開発で必要になる機能もひと通り揃っています。WebSocketもサポートしています。
内部的にはブロッキングI/Oとスレッドプールを使っています。大量の同時接続を捌くような用途には向きませんが、APIサーバーやツールの組み込みHTTP、テスト用のモックサーバーなど、多くのユースケースで十分な性能を発揮します。
「今日の課題を、今日中に解決する」— cpp-httplibが目指しているのは、そういうシンプルさです。
## ドキュメント
- [A Tour of cpp-httplib](tour/) — 基本を順を追って学べるチュートリアル。初めての方はここから
- [Cookbook](cookbook/) — 目的別のレシピ集。必要なトピックから読めます
- [Building a Desktop LLM App](llm-app/) — llama.cpp を組み込んだデスクトップアプリを段階的に構築する実践ガイド
+22
View File
@@ -0,0 +1,22 @@
---
title: "Building a Desktop LLM App with cpp-httplib"
order: 0
---
llama.cpp を組み込んだ LLM 翻訳デスクトップアプリを段階的に構築しながら、cpp-httplib のサーバー・クライアント両面の使い方を実践的に学びます。翻訳は一例であり、この部分を差し替えることで要約・コード生成・チャットボットなど自分のアプリに応用できます。
## 依存ライブラリ
- [llama.cpp](https://github.com/ggml-org/llama.cpp) — LLM 推論エンジン
- [nlohmann/json](https://github.com/nlohmann/json) — JSON パーサー(ヘッダーオンリー)
- [webview/webview](https://github.com/webview/webview) — WebView ラッパー(ヘッダーオンリー)
- [cpp-httplib](https://github.com/yhirose/cpp-httplib) — HTTP サーバー/クライアント(ヘッダーオンリー)
## 章立て
1. **llama.cpp を組み込んで REST API を作る** — テキストを POST すると翻訳結果を JSON で返すシンプルな API から始める
2. **SSE でトークンストリーミングを追加する** — 翻訳結果をトークン単位で逐次返す LLM API 標準の方式を実装する
3. **モデルの取得・管理機能を追加する** — Hugging Face から GGUF モデルを検索・ダウンロードするクライアント機能を実装する
4. **Web UI を追加する** — 静的ファイル配信で翻訳 UI をホストし、ブラウザから操作できるようにする
5. **WebView でデスクトップアプリ化する** — webview/webview で包み、Electron 的なデスクトップアプリとして動作させる
6. **llama.cpp 本家のサーバー実装をコードリーディング** — 自分で作ったものとプロダクション品質のコードを比較して学ぶ
@@ -0,0 +1,88 @@
---
title: "Getting Started"
order: 1
---
cpp-httplibを始めるのに必要なのは、`httplib.h`とC++コンパイラーだけです。ファイルをダウンロードして、Hello Worldサーバーを動かすところまでやってみましょう。
## httplib.h の入手
GitHubから直接ダウンロードできます。常に最新版を使ってください。
```sh
curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
```
ダウンロードした `httplib.h` をプロジェクトのディレクトリに置けば、準備完了です。
## コンパイラーの準備
| OS | 開発環境 | セットアップ |
| -- | -------- | ------------ |
| macOS | Apple Clang | Xcode Command Line Tools (`xcode-select --install`) |
| Ubuntu | clang++ または g++ | `apt install clang` または `apt install g++` |
| Windows | MSVC | Visual Studio 2022 以降(C++ コンポーネントを含めてインストール) |
## Hello World サーバー
次のコードを `server.cpp` として保存しましょう。
```cpp
#include "httplib.h"
int main() {
httplib::Server svr;
svr.Get("/", [](const httplib::Request&, httplib::Response& res) {
res.set_content("Hello, World!", "text/plain");
});
svr.listen("0.0.0.0", 8080);
}
```
たった数行で、HTTPリクエストに応答するサーバーが書けます。
## コンパイルと実行
このチュートリアルのサンプルコードは、コードを簡潔に書けるC++17で書いています。cpp-httplib自体はC++11でもコンパイルできます。
```sh
# 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
```
コンパイルできたら実行します。
```sh
# macOS / Linux
./server
# Windows
server.exe
```
ブラウザで `http://localhost:8080` を開いてください。"Hello, World!" と表示されれば成功です。
`curl` でも確認できます。
```sh
curl http://localhost:8080/
# Hello, World!
```
サーバーを停止するには、ターミナルで `Ctrl+C` を押します。
## 次のステップ
サーバーの基本がわかりましたね。次は、クライアント側を見てみましょう。cpp-httplibはHTTPクライアント機能も備えています。
**次:** [Basic Client](../02-basic-client)
+266
View File
@@ -0,0 +1,266 @@
---
title: "Basic Client"
order: 2
---
cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。`httplib::Client` を使って、GETやPOSTリクエストを送ってみましょう。
## テスト用サーバーの準備
クライアントの動作を確認するために、リクエストを受け付けるサーバーを用意します。次のコードを保存し、前章と同じ手順でコンパイル・実行してください。サーバーの詳しい解説は次章で行います。
```cpp
#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リクエストです。
```cpp
#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` コマンドはこうなります。
```sh
curl http://localhost:8080/hi
# Hello!
```
## レスポンスの確認
レスポンスには、ステータスコードとボディ以外にもヘッダー情報が含まれています。
```cpp
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->body``std::string` なので、JSON レスポンスをパースしたい場合は [nlohmann/json](https://github.com/nlohmann/json) などの JSON ライブラリにそのまま渡せます。
## クエリパラメーター
GETリクエストにクエリパラメーターを付けるには、URLに直接書くか、`httplib::Params` を使います。
```cpp
auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
if (res) {
std::cout << res->body << std::endl; // Query: cpp-httplib
}
```
`httplib::Params` を使うと、特殊文字のURLエンコードを自動で行ってくれます。
```sh
curl "http://localhost:8080/search?q=cpp-httplib"
# Query: cpp-httplib
```
## パスパラメーター
URLのパスに値を直接埋め込む場合も、クライアント側は特別なAPIは不要です。パスをそのまま `Get()` に渡すだけです。
```cpp
auto res = cli.Get("/users/42");
if (res) {
std::cout << res->body << std::endl; // User ID: 42
}
```
```sh
curl http://localhost:8080/users/42
# User ID: 42
```
テスト用サーバーには、正規表現でIDを数字のみに絞った `/files/(\d+)` もあります。
```cpp
auto res = cli.Get("/files/42");
if (res) {
std::cout << res->body << std::endl; // File ID: 42
}
```
```sh
curl http://localhost:8080/files/42
# File ID: 42
```
`/files/abc` のように数字以外を渡すと404が返ります。仕組みは次章で解説します。
## リクエストヘッダー
カスタムHTTPヘッダーを付けるには、`httplib::Headers` を渡します。`Get()``Post()` のどちらでも使えます。
```cpp
auto res = cli.Get("/hi", httplib::Headers{
{"Authorization", "Bearer my-token"}
});
```
```sh
curl -H "Authorization: Bearer my-token" http://localhost:8080/hi
```
## POSTリクエスト
テキストデータをPOSTしてみましょう。`Post()` の第2引数にボディ、第3引数にContent-Typeを指定します。
```cpp
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` はボディをそのまま返すので、送った文字列がそのまま返ってきます。
```sh
curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post
# Hello, Server!
```
## フォームデータの送信
HTMLフォームのように、キーと値のペアを送ることもできます。`httplib::Params` を使います。
```cpp
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` 形式で送信されます。
```sh
curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
```
## ファイルのPOST
ファイルをアップロードするには、`httplib::UploadFormDataItems` を使ってマルチパートフォームデータとして送信します。
```cpp
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つのフィールドで構成されます。
```sh
curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload
```
## エラーハンドリング
ネットワーク通信では、サーバーに接続できない場合があります。`res` が有効かどうかを必ず確認しましょう。
```cpp
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](../03-basic-server)
+280
View File
@@ -0,0 +1,280 @@
---
title: "Basic Server"
order: 3
---
前章ではクライアントからリクエストを送りました。そのとき、テスト用サーバーを用意しましたね。この章では、あのサーバーの仕組みをひとつずつ紐解いていきます。
## サーバーの起動
ルーティングを登録したら、最後に `svr.listen()` を呼んでサーバーを起動します。
```cpp
svr.listen("0.0.0.0", 8080);
```
第1引数はホスト、第2引数はポート番号です。`"0.0.0.0"` を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは `"127.0.0.1"` を使います。
`listen()` はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで `Ctrl+C` を押すか、別スレッドから `svr.stop()` を呼ぶまでサーバーは動き続けます。
## ルーティング
サーバーの核になるのは「ルーティング」です。どのURLに、どのHTTPメソッドでアクセスされたら、何をするか。それを登録する仕組みです。
```cpp
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メソッドごとにメソッドが用意されています。
```cpp
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` を使って短く書くこともできます。
```cpp
svr.Get("/hi", [](const auto &req, auto &res) {
res.set_content("Hello!", "text/plain");
});
```
パスが一致したときだけハンドラーが呼ばれます。登録されていないパスにアクセスすると、自動的に404が返ります。
## リクエストオブジェクト
ハンドラーの第1引数 `req` から、クライアントが送ってきた情報を読み取れます。
### ボディ
`req.body` でリクエストボディを取得できます。型は `std::string` です。
```cpp
svr.Post("/post", [](const auto &req, auto &res) {
// クライアントが送ったボディをそのまま返す
res.set_content(req.body, "text/plain");
});
```
### ヘッダー
`req.get_header_value()` でリクエストヘッダーの値を取得できます。
```cpp
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のフォームデータの両方に使えます。
```cpp
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` を使います。
```cpp
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()` で取得します。
```cpp
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/42``42` を取得したい場合です。`:param` 記法を使うと、URLの一部をキャプチャできます。
```cpp
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"` です。
複数のパスパラメーターも使えます。
```cpp
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` です。
```cpp
// 数字のみの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のレスポンスが返ります。
```cpp
svr.Get("/hi", [](const auto &req, auto &res) {
res.set_content("Hello!", "text/plain");
});
```
### ステータスコード
ステータスコードを変えたいときは、`res.status` に代入します。
```cpp
svr.Get("/not-found", [](const auto &req, auto &res) {
res.status = 404;
res.set_content("Not found", "text/plain");
});
```
### レスポンスヘッダー
`res.set_header()` でレスポンスヘッダーを追加できます。
```cpp
svr.Get("/with-header", [](const auto &req, auto &res) {
res.set_header("X-Custom", "my-value");
res.set_content("Hello!", "text/plain");
});
```
## 前章のサーバーを読み解く
ここまでの知識を使って、前章で用意したテスト用サーバーを改めて見てみましょう。
### GET /hi
```cpp
svr.Get("/hi", [](const auto &, auto &res) {
res.set_content("Hello!", "text/plain");
});
```
最もシンプルなハンドラーです。リクエストの情報は使わないので、`req` の変数名を省略しています。`"Hello!"` というテキストをそのまま返します。
### GET /search
```cpp
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
```cpp
svr.Post("/post", [](const auto &req, auto &res) {
res.set_content(req.body, "text/plain");
});
```
クライアントが送ったリクエストボディを、そのままレスポンスとして返すエコーサーバーです。`req.body` にボディが丸ごと入っています。
### POST /submit
```cpp
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
```cpp
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.filename``f.content.size()` でファイル名とサイズを返しています。
### GET /users/:id
```cpp
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+)
```cpp
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](../04-static-file-server)
@@ -0,0 +1,134 @@
---
title: "Static File Server"
order: 4
---
cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。`set_mount_point()` を1行呼ぶだけです。
## set_mount_point の基本
さっそくやってみましょう。`set_mount_point()` は、URLのパスとローカルディレクトリを紐づけます。
```cpp
#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` を置きます。
```sh
mkdir html
```
```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>
```
コンパイルして起動します。
```sh
g++ -std=c++17 -o server server.cpp -pthread
./server
```
ブラウザで `http://localhost:8080` を開いてみてください。`html/index.html` の内容が表示されるはずです。`http://localhost:8080/index.html` でも同じページが返ります。
もちろん、前章のクライアントコードや `curl` でもアクセスできますよ。
```cpp
httplib::Client cli("http://localhost:8080");
auto res = cli.Get("/");
if (res) {
std::cout << res->body << std::endl; // HTMLが表示される
}
```
```sh
curl http://localhost:8080
```
## 複数のマウントポイント
`set_mount_point()` は何回でも呼べます。URLのパスごとに、別々のディレクトリを割り当てられます。
```cpp
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` を配信します。
## ハンドラーとの組み合わせ
静的ファイルの配信と、前章で学んだルーティングハンドラーは共存できます。
```cpp
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引数にヘッダーを渡すと、静的ファイルのレスポンスにカスタムヘッダーを付けられます。キャッシュ制御に便利です。
```cpp
svr.set_mount_point("/", "./public", {
{"Cache-Control", "max-age=3600"}
});
```
こうすると、ブラウザは配信されたファイルを1時間キャッシュします。
## 静的ファイルサーバー用のDockerファイル
cpp-httplibのリポジトリには、静的ファイルサーバー用の `Dockerfile` が含まれています。Docker Hubにビルド済みイメージも公開しているので、1コマンドで起動できます。
```sh
> 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](../05-tls-setup)
+88
View File
@@ -0,0 +1,88 @@
---
title: "TLS Setup"
order: 5
---
ここまではHTTP(平文)でやってきましたが、実際のWebではHTTPS(暗号化通信)が当たり前ですよね。cpp-httplibでHTTPSを使うには、TLSライブラリが必要です。
このTourではOpenSSLを使います。最も広く使われていて、情報も豊富です。
## OpenSSLのインストール
お使いのOSに合わせてインストールしましょう。
| OS | インストール方法 |
| -- | ---------------- |
| macOS | [Homebrew](https://brew.sh/) (`brew install openssl`) |
| Ubuntu / Debian | `sudo apt install libssl-dev` |
| Windows | [vcpkg](https://vcpkg.io/) (`vcpkg install openssl`) |
## コンパイルオプション
TLS機能を有効にするには、`CPPHTTPLIB_OPENSSL_SUPPORT` マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。
```sh
# 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を渡してアクセスするだけのプログラムです。
```cpp
#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に対応しています。マクロ定義とリンクするライブラリを変えるだけで切り替えられます。
| バックエンド | マクロ定義 | リンクするライブラリ |
| :--- | :--- | :--- |
| OpenSSL | `CPPHTTPLIB_OPENSSL_SUPPORT` | `libssl`, `libcrypto` |
| Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` |
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` |
このTourではOpenSSLを前提に進めますが、APIはどのバックエンドでも共通です。
## 次のステップ
TLSの準備ができましたね。次は、HTTPSサイトにリクエストを送ってみましょう。
**次:** [HTTPS Client](../06-https-client)
+122
View File
@@ -0,0 +1,122 @@
---
title: "HTTPS Client"
order: 6
---
前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った `httplib::Client` がそのまま使えます。コンストラクタに `https://` 付きのURLを渡すだけです。
## GETリクエスト
実在するHTTPSサイトにアクセスしてみましょう。
```cpp
#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はすべてそのまま使えます。
```sh
curl https://nghttp2.org/
```
## ポートの指定
HTTPSのデフォルトポートは443です。別のポートを使いたい場合は、URLにポートを含めます。
```cpp
httplib::Client cli("https://localhost:8443");
```
## CA証明書の検証
`httplib::Client` はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。
CA証明書は、macOSならKeychain、LinuxならシステムのCA証明書ストア、WindowsならWindowsの証明書ストアから自動で読み込みます。ほとんどの場合、追加の設定は要りません。
### CA証明書ファイルの指定
環境によってはシステムのCA証明書が見つからないこともあります。そのときは `set_ca_cert_path()` でパスを直接指定してください。
```cpp
httplib::Client cli("https://nghttp2.org");
cli.set_ca_cert_path("/etc/ssl/certs/ca-certificates.crt");
auto res = cli.Get("/");
```
```sh
curl --cacert /etc/ssl/certs/ca-certificates.crt https://nghttp2.org/
```
### 証明書検証の無効化
開発中、自己署名証明書のサーバーに接続したいときは、検証を無効にできます。
```cpp
httplib::Client cli("https://localhost:8443");
cli.enable_server_certificate_verification(false);
auto res = cli.Get("/");
```
```sh
curl -k https://localhost:8443/
```
本番では絶対に無効にしないでください。中間者攻撃のリスクがあります。
## リダイレクトの追跡
HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば `http://` から `https://` へ、あるいは `www` なしから `www` ありへ転送されるケースです。
デフォルトではリダイレクトを追跡しません。リダイレクト先は `Location` ヘッダーで確認できます。
```cpp
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;
}
```
```sh
curl https://nghttp2.org/httpbin/redirect/3
```
`set_follow_location(true)` を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。
```cpp
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(最終的なレスポンス)
}
```
```sh
curl -L https://nghttp2.org/httpbin/redirect/3
```
## 次のステップ
HTTPSクライアントの使い方がわかりましたね。次は自分でHTTPSサーバーを立ててみましょう。自己署名証明書の作り方から始めます。
**次:** [HTTPS Server](../07-https-server)
+124
View File
@@ -0,0 +1,124 @@
---
title: "HTTPS Server"
order: 7
---
前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の `httplib::Server``httplib::SSLServer` に置き換えるだけです。
ただし、TLSサーバーにはサーバー証明書と秘密鍵が必要です。まずはそこから準備しましょう。
## 自己署名証明書の作成
開発やテスト用なら、自己署名証明書(いわゆるオレオレ証明書)で十分です。OpenSSLのコマンドでサクッと作れます。
```sh
openssl req -x509 -noenc -keyout key.pem -out cert.pem -subj /CN=localhost
```
これで2つのファイルができます。
- **`cert.pem`** — サーバー証明書
- **`key.pem`** — 秘密鍵
## 最小のHTTPSサーバー
証明書ができたら、さっそくサーバーを書いてみましょう。
```cpp
#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` オプションで証明書検証をスキップします。
```sh
curl -k https://localhost:8443/
# Hello, HTTPS!
```
ブラウザで `https://localhost:8443` を開くと、「この接続は安全ではありません」と警告が出ます。自己署名証明書なので正常です。気にせず進めてください。
## クライアントからの接続
前章の `httplib::Client` で接続してみましょう。自己署名証明書のサーバーに接続するには、2つの方法があります。
### 方法1: 証明書検証を無効にする
開発時の手軽な方法です。
```cpp
#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証明書として信頼するよう指定します。
```cpp
#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::Server` | `httplib::SSLServer` |
| -- | ------------------ | -------------------- |
| コンストラクタ | 引数なし | 証明書と秘密鍵のパス |
| プロトコル | HTTP | HTTPS |
| ポート(慣例) | 8080 | 8443 |
| ルーティング | 共通 | 共通 |
HTTPサーバーをHTTPSに切り替えるには、コンストラクタを変えるだけです。
## 次のステップ
HTTPSサーバーが動きましたね。これでHTTP/HTTPSのクライアントとサーバー、両方の基本がそろいました。
次は、cpp-httplibに新しく加わったWebSocket機能を見てみましょう。
**次:** [WebSocket](../08-websocket)
+139
View File
@@ -0,0 +1,139 @@
---
title: "WebSocket"
order: 8
---
cpp-httplibはWebSocketにも対応しています。HTTPのリクエスト/レスポンスと違い、WebSocketはサーバーとクライアントが双方向にメッセージをやり取りできます。チャットやリアルタイム通知に便利です。
さっそく、エコーサーバーとクライアントを作ってみましょう。
## エコーサーバー
受け取ったメッセージをそのまま返すエコーサーバーです。
```cpp
#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` を使ってサーバーに接続してみましょう。
```cpp
#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()` の戻り値で区別できます。
```cpp
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リクエスト情報を読み取れます。認証トークンの確認などに便利です。
```cpp
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ハンドラーを登録するだけです。
```cpp
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://` スキームを使います。
```cpp
httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
```
## 次のステップ
WebSocketの基本がわかりましたね。ここまでで Tourは終わりです。
次のページでは、Tourで取り上げなかった機能をまとめて紹介します。
**次:** [What's Next](../09-whats-next)
+228
View File
@@ -0,0 +1,228 @@
---
title: "What's Next"
order: 9
---
Tourお疲れさまでした! cpp-httplibの基本はひと通り押さえましたね。でも、まだまだ便利な機能があります。Tourで取り上げなかった機能をカテゴリー別に紹介します。
## Streaming API
LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。`stream::Get()` を使えば、データをチャンクごとに処理できます。
```cpp
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と併用できます。
```cpp
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()` があります。サイズがわかっているなら前者、不明なら後者を使ってください。
```cpp
// サイズ指定あり(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()` が便利です。ファイルを全部メモリに読み込まず、ストリーミングで送れます。
```cpp
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` による再開にも対応しています。
```cpp
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(); // ブロッキング、自動再接続あり
```
イベントタイプごとにハンドラーを分けることもできますよ。
```cpp
sse.on_event("update", [](const httplib::sse::SSEMessage &msg) {
// "update" イベントだけ処理
});
```
## 認証
クライアントにはBasic認証、Bearer Token認証、Digest認証のヘルパーを用意しています。
```cpp
httplib::Client cli("https://api.example.com");
cli.set_basic_auth("user", "password");
cli.set_bearer_token_auth("my-token");
```
## 圧縮
gzip、Brotli、Zstandardによる圧縮・展開に対応しています。使いたい方式のマクロを定義してコンパイルしましょう。
| 圧縮方式 | マクロ定義 |
| -- | -- |
| gzip | `CPPHTTPLIB_ZLIB_SUPPORT` |
| Brotli | `CPPHTTPLIB_BROTLI_SUPPORT` |
| Zstandard | `CPPHTTPLIB_ZSTD_SUPPORT` |
```cpp
httplib::Client cli("https://example.com");
cli.set_compress(true); // リクエストボディを圧縮
cli.set_decompress(true); // レスポンスボディを展開
```
## プロキシ
HTTPプロキシ経由で接続できます。
```cpp
httplib::Client cli("https://example.com");
cli.set_proxy("proxy.example.com", 8080);
cli.set_proxy_basic_auth("user", "password");
```
## タイムアウト
接続・読み取り・書き込みのタイムアウトを個別に設定できます。
```cpp
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接続を再利用するので効率的です。
```cpp
httplib::Client cli("https://example.com");
cli.set_keep_alive(true);
```
## サーバーのミドルウェア
リクエスト処理の前後にフックを挟めます。
```cpp
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");
});
```
`res.user_data` を使うと、ミドルウェアからハンドラーにデータを渡せます。認証トークンのデコード結果を共有するときに便利です。
```cpp
svr.set_pre_routing_handler([](const auto &req, auto &res) {
res.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>(res.user_data.at("auth_user"));
res.set_content("Hello, " + user, "text/plain");
});
```
エラーや例外のハンドラーもカスタマイズできますよ。
```cpp
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");
});
```
## ロギング
サーバーでもクライアントでもロガーを設定できます。
```cpp
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での通信にも対応しています。同じマシン上のプロセス間通信に使えます。
```cpp
// サーバー
httplib::Server svr;
svr.set_address_family(AF_UNIX);
svr.listen("/tmp/httplib.sock", 0);
```
```cpp
// クライアント
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](https://github.com/yhirose/cpp-httplib/blob/master/README.md) — 全APIのリファレンス
- [README-sse](https://github.com/yhirose/cpp-httplib/blob/master/README-sse.md) — Server-Sent Eventsの使い方
- [README-stream](https://github.com/yhirose/cpp-httplib/blob/master/README-stream.md) — Streaming APIの使い方
- [README-websocket](https://github.com/yhirose/cpp-httplib/blob/master/README-websocket.md) — WebSocketサーバーの使い方
+16
View File
@@ -0,0 +1,16 @@
---
title: "A Tour of cpp-httplib"
order: 0
---
cpp-httplibの基本を、順番に学んでいくチュートリアルです。各章は前の章の内容を踏まえて進む構成なので、1章から順に読んでください。
1. [Getting Started](01-getting-started) — httplib.h の入手とHello Worldサーバー
2. [Basic Client](02-basic-client) — GET/POST・パスパラメーターのリクエスト送信
3. [Basic Server](03-basic-server) — ルーティング、パスパラメーター、レスポンスの組み立て
4. [Static File Server](04-static-file-server) — 静的ファイルの配信
5. [TLS Setup](05-tls-setup) — OpenSSL / mbedTLS のセットアップ
6. [HTTPS Client](06-https-client) — HTTPSサイトへのリクエスト
7. [HTTPS Server](07-https-server) — HTTPSサーバーの構築
8. [WebSocket](08-websocket) — WebSocket通信の基本
9. [What's Next](09-whats-next) — さらなる機能の紹介
+452 -220
View File
File diff suppressed because it is too large Load Diff
+10
View File
@@ -36,6 +36,7 @@ others:
@(cd test && make fuzz_test)
@(cd test && make test_websocket_heartbeat && ./test_websocket_heartbeat)
@(cd test && make test_thread_pool && ./test_thread_pool)
@(cd test && make test_benchmark && ./test_benchmark)
build:
@(cd test && make test_split)
@@ -44,3 +45,12 @@ build:
bench:
@(cd benchmark && make bench-all)
docs:
@cargo build --release --manifest-path docs-gen/Cargo.toml
@./docs-gen/target/release/docs-gen build docs-src --out docs
docs-serve:
@cargo build --release --manifest-path docs-gen/Cargo.toml
-@./docs-gen/target/release/docs-gen serve docs-src --open
+11 -1
View File
@@ -219,6 +219,16 @@ style_check: $(STYLE_CHECK_FILES)
echo "All files are properly formatted."; \
fi
BENCHMARK_LIBS = -lpthread
ifneq ($(OS), Windows_NT)
ifeq ($(shell uname -s), Darwin)
BENCHMARK_LIBS += -framework CoreFoundation -framework CFNetwork
endif
endif
test_benchmark : test_benchmark.cc ../httplib.h Makefile
$(CXX) -o $@ -I.. $(CXXFLAGS) test_benchmark.cc gtest/src/gtest-all.cc gtest/src/gtest_main.cc -Igtest -Igtest/include $(BENCHMARK_LIBS)
test_websocket_heartbeat : test_websocket_heartbeat.cc ../httplib.h Makefile
$(CXX) -o $@ -I.. $(CXXFLAGS) test_websocket_heartbeat.cc $(TEST_ARGS)
@file $@
@@ -254,5 +264,5 @@ cert.pem:
./gen-certs.sh
clean:
rm -rf test test_split test_mbedtls test_split_mbedtls test_wolfssl test_split_wolfssl test_no_tls, test_split_no_tls test_proxy test_proxy_mbedtls test_proxy_wolfssl server_fuzzer *.pem *.0 *.o *.1 *.srl httplib.h httplib.cc _build* *.dSYM *_shard_*.log
rm -rf test test_split test_mbedtls test_split_mbedtls test_wolfssl test_split_wolfssl test_no_tls, test_split_no_tls test_proxy test_proxy_mbedtls test_proxy_wolfssl test_benchmark server_fuzzer *.pem *.0 *.o *.1 *.srl httplib.h httplib.cc _build* *.dSYM *_shard_*.log cpp-httplib
+1
View File
@@ -15,6 +15,7 @@ acl localnet src fc00::/7 # RFC 4193 local private network range
acl localnet src fe80::/10 # RFC 4291 link-local (directly plugged) machines
acl SSL_ports port 443
acl SSL_ports port 1025-65535
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 # https
+1
View File
@@ -15,6 +15,7 @@ acl localnet src fc00::/7 # RFC 4193 local private network range
acl localnet src fe80::/10 # RFC 4291 link-local (directly plugged) machines
acl SSL_ports port 443
acl SSL_ports port 1025-65535
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 # https
+8
View File
@@ -0,0 +1,8 @@
services:
squid_basic:
extra_hosts:
- "host.docker.internal:host-gateway"
squid_digest:
extra_hosts:
- "host.docker.internal:host-gateway"
+460 -187
View File
@@ -102,71 +102,6 @@ static void read_file(const std::string &path, std::string &out) {
fs.read(&out[0], static_cast<std::streamsize>(size));
}
void performance_test(const char *host) {
Server svr;
svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
res.set_content("Benchmark Response", "text/plain");
});
auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
auto se = detail::scope_exit([&] {
svr.stop();
listen_thread.join();
ASSERT_FALSE(svr.is_running());
});
svr.wait_until_ready();
Client cli(host, PORT);
// Warm-up request to establish connection and resolve DNS
auto warmup_res = cli.Get("/benchmark");
ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
// Run multiple trials and collect timings
const int num_trials = 20;
std::vector<int64_t> timings;
timings.reserve(num_trials);
for (int i = 0; i < num_trials; i++) {
auto start = std::chrono::high_resolution_clock::now();
auto res = cli.Get("/benchmark");
auto end = std::chrono::high_resolution_clock::now();
auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
.count();
// Assertions after timing measurement to avoid overhead
ASSERT_TRUE(res);
EXPECT_EQ(StatusCode::OK_200, res->status);
timings.push_back(elapsed);
}
// Calculate 25th percentile (lower quartile)
std::sort(timings.begin(), timings.end());
auto p25 = timings[num_trials / 4];
// Format timings for output
std::ostringstream timings_str;
timings_str << "[";
for (size_t i = 0; i < timings.size(); i++) {
if (i > 0) timings_str << ", ";
timings_str << timings[i];
}
timings_str << "]";
// Localhost HTTP GET should be fast even in CI environments
EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
<< "ms (Issue #1777). Timings: " << timings_str.str();
}
TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
TEST(BenchmarkTest, v6) { performance_test("::1"); }
class UnixSocketTest : public ::testing::Test {
protected:
void TearDown() override { std::remove(pathname_.c_str()); }
@@ -413,6 +348,38 @@ TEST(DecodePathTest, PercentCharacterNUL) {
EXPECT_EQ(decode_path_component("x%00x"), expected);
}
TEST(DecodePathTest, UnicodeEncoding) {
// %u0041 = 'A' (1-byte UTF-8)
EXPECT_EQ("A", decode_path_component("%u0041"));
// %u00E9 = 'é' (2-byte UTF-8)
EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
// %u3042 = 'あ' (3-byte UTF-8)
EXPECT_EQ(U8(""), decode_path_component("%u3042"));
// %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
EXPECT_FALSE(decode_path_component("%uFFFF").empty());
// %uD800 = surrogate (invalid, silently dropped)
EXPECT_EQ("", decode_path_component("%uD800"));
}
TEST(SanitizeFilenameTest, VariousPatterns) {
// Path traversal
EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
// Normal and edge cases
EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
EXPECT_EQ("filename.txt",
httplib::sanitize_filename("/path/to/filename.txt"));
EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
EXPECT_EQ("", httplib::sanitize_filename(".."));
EXPECT_EQ("", httplib::sanitize_filename(""));
// Null bytes stripped
EXPECT_EQ("safe.txt",
httplib::sanitize_filename(std::string("safe\0.txt", 9)));
// Whitespace-only rejected
EXPECT_EQ("", httplib::sanitize_filename(" "));
}
TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
string unescapedCharacters = "-_.!~*'()";
@@ -1235,6 +1202,89 @@ TEST(ParseAcceptEncoding3, AcceptEncoding) {
#endif
}
TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
// All supported encodings rejected with q=0 should return None
Request req;
req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
Response res;
res.set_header("Content-Type", "text/plain");
auto ret = detail::encoding_type(req, res);
EXPECT_TRUE(ret == detail::EncodingType::None);
}
TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
// q=0.0, q=0.00, q=0.000 should also be treated as rejected
Request req;
req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
Response res;
res.set_header("Content-Type", "text/plain");
auto ret = detail::encoding_type(req, res);
EXPECT_TRUE(ret == detail::EncodingType::None);
}
TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
// x-gzip;q=0 should not cause "gzip" to be incorrectly detected
Request req;
req.set_header("Accept-Encoding", "x-gzip;q=0");
Response res;
res.set_header("Content-Type", "text/plain");
auto ret = detail::encoding_type(req, res);
EXPECT_TRUE(ret == detail::EncodingType::None);
}
TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
// RFC 7231: Accept-Encoding values are case-insensitive
Request req;
req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
Response res;
res.set_header("Content-Type", "text/plain");
auto ret = detail::encoding_type(req, res);
#ifdef CPPHTTPLIB_BROTLI_SUPPORT
EXPECT_TRUE(ret == detail::EncodingType::Brotli);
#elif CPPHTTPLIB_ZLIB_SUPPORT
EXPECT_TRUE(ret == detail::EncodingType::Gzip);
#elif CPPHTTPLIB_ZSTD_SUPPORT
EXPECT_TRUE(ret == detail::EncodingType::Zstd);
#else
EXPECT_TRUE(ret == detail::EncodingType::None);
#endif
}
TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
// q value should determine priority, not hardcoded order
Request req;
req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
Response res;
res.set_header("Content-Type", "text/plain");
auto ret = detail::encoding_type(req, res);
// gzip has highest q=1.0, so it should be selected even though
// br and zstd are also supported
#ifdef CPPHTTPLIB_ZLIB_SUPPORT
EXPECT_TRUE(ret == detail::EncodingType::Gzip);
#elif CPPHTTPLIB_ZSTD_SUPPORT
EXPECT_TRUE(ret == detail::EncodingType::Zstd);
#elif CPPHTTPLIB_BROTLI_SUPPORT
EXPECT_TRUE(ret == detail::EncodingType::Brotli);
#else
EXPECT_TRUE(ret == detail::EncodingType::None);
#endif
}
TEST(BufferStreamTest, read) {
detail::BufferStream strm1;
Stream &strm = strm1;
@@ -2330,6 +2380,31 @@ TEST(RedirectToDifferentPort, Redirect) {
EXPECT_EQ("Hello World!", res->body);
}
TEST(RedirectToDifferentPort, OverflowPortNumber) {
Server svr;
svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
// Port number that overflows int — should not crash
res.set_redirect("http://localhost:99999999999999999999/target");
});
auto port = svr.bind_to_any_port(HOST);
auto thread = std::thread([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
thread.join();
ASSERT_FALSE(svr.is_running());
});
svr.wait_until_ready();
Client cli(HOST, port);
cli.set_follow_location(true);
auto res = cli.Get("/redir");
// Should fail gracefully, not crash (no valid response due to bad port)
EXPECT_FALSE(res);
}
TEST(RedirectFromPageWithContent, Redirect) {
Server svr;
@@ -2512,7 +2587,7 @@ TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
}
}
TEST(BindServerTest, DISABLED_BindDualStack) {
TEST(BindServerTest, BindDualStack) {
Server svr;
svr.Get("/1", [&](const Request & /*req*/, Response &res) {
@@ -5605,7 +5680,13 @@ TEST_F(ServerTest, PutLargeFileWithGzip2) {
// depending on the zlib library.
EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
static_cast<uint64_t>(10 * 1024 * 1024));
#ifdef CPPHTTPLIB_BROTLI_SUPPORT
EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
#elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
#elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
#endif
}
TEST_F(ServerTest, PutContentWithDeflate) {
@@ -5746,53 +5827,6 @@ TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
ASSERT_EQ(original_text, decompressed_data);
}
#ifdef _WIN32
TEST(GzipDecompressor, LargeRandomData) {
// prepare large random data that is difficult to be compressed and is
// expected to have large size even when compressed
std::random_device seed_gen;
std::mt19937 random(seed_gen());
constexpr auto large_size_byte = 4294967296UL; // 4GiB
constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
std::generate(data.begin(), data.end(), [&]() { return random(); });
// compress data over 4GiB
std::string compressed_data;
compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
httplib::detail::gzip_compressor compressor;
auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
data.size() * sizeof(std::uint32_t), true,
[&](const char *data, size_t size) {
compressed_data.insert(
compressed_data.size(), data, size);
return true;
});
ASSERT_TRUE(result);
// FIXME: compressed data size is expected to be greater than 4GiB,
// but there is no guarantee
// ASSERT_TRUE(compressed_data.size() >= large_size_byte);
// decompress data over 4GiB
std::string decompressed_data;
decompressed_data.reserve(data_size);
httplib::detail::gzip_decompressor decompressor;
result = decompressor.decompress(
compressed_data.data(), compressed_data.size(),
[&](const char *data, size_t size) {
decompressed_data.insert(decompressed_data.size(), data, size);
return true;
});
ASSERT_TRUE(result);
// compare
ASSERT_EQ(data_size, decompressed_data.size());
ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
0);
}
#endif
#endif
#ifdef CPPHTTPLIB_BROTLI_SUPPORT
@@ -5815,6 +5849,47 @@ TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ(std::string("123456789"), res->body);
}
TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
cli_.set_compress(true);
auto res = cli_.Put(
"/put", 3,
[](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
sink.os << "PUT";
return true;
},
"text/plain");
ASSERT_TRUE(res);
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ("PUT", res->body);
}
TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
cli_.set_compress(true);
auto res = cli_.Put(
"/put",
[](size_t /*offset*/, DataSink &sink) {
sink.os << "PUT";
sink.done();
return true;
},
"text/plain");
ASSERT_TRUE(res);
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ("PUT", res->body);
}
TEST_F(ServerTest, PutLargeFileWithBrotli) {
cli_.set_compress(true);
auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
ASSERT_TRUE(res);
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ(LARGE_DATA, res->body);
EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
}
#endif
TEST_F(ServerTest, Patch) {
@@ -9441,6 +9516,18 @@ TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
ASSERT_EQ(1234, cli.port());
}
TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
// Port number that overflows int — should not crash, client becomes invalid
httplib::Client cli("http://www.google.com:99999999999999999999");
ASSERT_FALSE(cli.is_valid());
}
TEST(HostAndPortPropertiesTest, PortOutOfRange) {
// Port 99999 exceeds valid range (1-65535) — should not crash
httplib::Client cli("http://www.google.com:99999");
ASSERT_FALSE(cli.is_valid());
}
#ifdef CPPHTTPLIB_SSL_ENABLED
TEST(HostAndPortPropertiesTest, SSL) {
httplib::SSLClient cli("www.google.com");
@@ -10713,38 +10800,6 @@ TEST(ClientImplMethods, GetSocketTest) {
}
}
// Disabled due to out-of-memory problem on GitHub Actions
#ifdef _WIN64
TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
// allocate content size larger than 2GB in memory
const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
char *content = (char *)malloc(content_size);
ASSERT_TRUE(content);
Server svr;
svr.Get("/foo",
[=](const httplib::Request & /*req*/, httplib::Response &res) {
res.set_content(content, content_size, "application/octet-stream");
});
auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
auto se = detail::scope_exit([&] {
svr.stop();
listen_thread.join();
if (content) free(content);
ASSERT_FALSE(svr.is_running());
});
svr.wait_until_ready();
Client cli(HOST, PORT);
auto res = cli.Get("/foo");
ASSERT_TRUE(res);
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ(content_size, res->body.length());
}
#endif
#ifdef CPPHTTPLIB_SSL_ENABLED
TEST(YahooRedirectTest2, SimpleInterface_Online) {
Client cli("http://yahoo.com");
@@ -11609,6 +11664,55 @@ TEST(MultipartFormDataTest, AlternateFilename) {
ASSERT_TRUE(send_request(1, req));
}
TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
auto handled = false;
Server svr;
svr.Post("/test", [&](const Request &req, Response &res) {
// Case-insensitive "utf-8''" prefix with a long value
const auto &file = req.form.get_file("file1");
ASSERT_EQ("file1", file.name);
// 8000 chars exercises both the Content-Disposition parser and the
// filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
// Prior to the fix, std::regex_match on this header would cause O(N)
// stack recursion in libstdc++, leading to SIGSEGV.
std::string expected_filename(8000, 'A');
ASSERT_EQ(expected_filename, file.filename);
res.set_content("ok", "text/plain");
handled = true;
});
thread t = thread([&] { svr.listen(HOST, PORT); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
ASSERT_FALSE(svr.is_running());
ASSERT_TRUE(handled);
});
svr.wait_until_ready();
// Build body with a long filename* value using mixed-case prefix "Utf-8''"
// Regression test for GHSA-qq6v-r583-3h69
std::string long_filename(8000, 'A');
std::string body = "----------\r\n"
"Content-Disposition: form-data; name=\"file1\"; "
"filename*=\"Utf-8''" +
long_filename +
"\"\r\n"
"\r\n"
"hello\r\n"
"------------\r\n";
auto req = "POST /test HTTP/1.1\r\n"
"Content-Type: multipart/form-data;boundary=--------\r\n"
"Content-Length: " +
std::to_string(body.size()) + "\r\n\r\n" + body;
ASSERT_TRUE(send_request(1, req));
}
TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
auto handled = false;
@@ -13002,6 +13106,66 @@ TEST(ClientInThreadTest, Issue2068) {
}
}
TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
auto handled = false;
Server svr;
svr.Post("/test", [&](const Request &, Response &) { handled = true; });
thread t = thread([&]() { svr.listen(HOST, PORT); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
ASSERT_FALSE(svr.is_running());
ASSERT_FALSE(handled);
});
svr.wait_until_ready();
// Two Content-Length headers with different values — must be rejected
auto req = "POST /test HTTP/1.1\r\n"
"Content-Length: 5\r\n"
"Content-Length: 10\r\n"
"\r\n"
"hello";
std::string response;
ASSERT_TRUE(send_request(1, req, &response));
ASSERT_EQ("HTTP/1.1 400 Bad Request",
response.substr(0, response.find("\r\n")));
}
TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
auto handled = false;
Server svr;
svr.Post("/test", [&](const Request &, Response &res) {
handled = true;
res.set_content("ok", "text/plain");
});
thread t = thread([&]() { svr.listen(HOST, PORT); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
ASSERT_FALSE(svr.is_running());
ASSERT_TRUE(handled);
});
svr.wait_until_ready();
// Two Content-Length headers with same value — should be accepted (RFC 9110)
auto req = "POST /test HTTP/1.1\r\n"
"Content-Length: 5\r\n"
"Content-Length: 5\r\n"
"\r\n"
"hello";
std::string response;
ASSERT_TRUE(send_request(1, req, &response));
ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
}
TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
Server svr;
@@ -13663,6 +13827,102 @@ TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
}
static std::thread serve_single_response(int port,
const std::string &response) {
return std::thread([port, response] {
auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
default_socket_options(srv);
detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(static_cast<uint16_t>(port));
::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
int opt = 1;
::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
#ifdef _WIN32
reinterpret_cast<const char *>(&opt),
#else
&opt,
#endif
sizeof(opt));
::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
::listen(srv, 1);
sockaddr_in cli_addr{};
socklen_t cli_len = sizeof(cli_addr);
auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
if (cli != INVALID_SOCKET) {
char buf[4096];
::recv(cli, buf, sizeof(buf), 0);
::send(cli,
#ifdef _WIN32
static_cast<const char *>(response.c_str()),
static_cast<int>(response.size()),
#else
response.c_str(), response.size(),
#endif
0);
detail::close_socket(cli);
}
detail::close_socket(srv);
});
}
TEST(OpenStreamMalformedContentLength, InvalidArgument) {
#ifndef _WIN32
signal(SIGPIPE, SIG_IGN);
#endif
auto server_thread =
serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: not-a-number\r\n"
"Connection: close\r\n"
"\r\n"
"hello");
std::this_thread::sleep_for(std::chrono::milliseconds(200));
Client cli("127.0.0.1", PORT + 2);
auto handle = cli.open_stream("GET", "/");
EXPECT_FALSE(handle.is_valid());
server_thread.join();
}
TEST(OpenStreamMalformedContentLength, OutOfRange) {
#ifndef _WIN32
signal(SIGPIPE, SIG_IGN);
#endif
auto server_thread = serve_single_response(
PORT + 4, "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 99999999999999999999999999\r\n"
"Connection: close\r\n"
"\r\n"
"hello");
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// Before the fix, std::stoull would throw std::out_of_range here and
// crash the process. After the fix, strtoull silently clamps to
// ULLONG_MAX so the stream opens without crashing. The important thing
// is that the process does NOT terminate.
Client cli("127.0.0.1", PORT + 4);
auto handle = cli.open_stream("GET", "/");
EXPECT_TRUE(handle.is_valid());
server_thread.join();
}
#ifdef CPPHTTPLIB_ZLIB_SUPPORT
TEST_F(OpenStreamTest, Gzip) {
Client cli("127.0.0.1", port_);
@@ -15891,48 +16151,6 @@ TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
}
// Disabled due to the out-of-memory problem on GitHub Actions Workflows
TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
// prepare large data
std::random_device seed_gen;
std::mt19937 random(seed_gen());
constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
// server
SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
ASSERT_TRUE(svr.is_valid());
svr.Post("/binary", [&](const Request &req, Response &res) {
EXPECT_EQ(large_size_byte, req.body.size());
EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
res.set_content(req.body, "application/octet-stream");
});
auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
auto se = detail::scope_exit([&] {
svr.stop();
listen_thread.join();
ASSERT_FALSE(svr.is_running());
});
svr.wait_until_ready();
// client POST
SSLClient cli("localhost", PORT);
cli.enable_server_certificate_verification(false);
cli.set_read_timeout(std::chrono::seconds(100));
cli.set_write_timeout(std::chrono::seconds(100));
auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
large_size_byte, "application/octet-stream");
// compare
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ(large_size_byte, res->body.size());
EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
}
#endif
// ============================================================================
@@ -16280,6 +16498,14 @@ TEST(WebSocketTest, InvalidURL) {
// Missing host
ws::WebSocketClient ws4("ws://:8080/path");
EXPECT_FALSE(ws4.is_valid());
// Port number overflow — should not crash
ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
EXPECT_FALSE(ws5.is_valid());
// Port out of range
ws::WebSocketClient ws6("ws://localhost:99999/path");
EXPECT_FALSE(ws6.is_valid());
}
TEST(WebSocketTest, UnsupportedScheme) {
@@ -16794,3 +17020,50 @@ TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
client.close();
}
#endif
#if !defined(_WIN32)
TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
auto secret_dir = std::string("./symlink_test_secret");
auto served_dir = std::string("./symlink_test_served");
auto secret_file = secret_dir + "/secret.txt";
auto symlink_path = served_dir + "/escape";
// Setup: create directories and files
mkdir(secret_dir.c_str(), 0755);
mkdir(served_dir.c_str(), 0755);
{
std::ofstream ofs(secret_file);
ofs << "SECRET_DATA";
}
// Create symlink using absolute path so it resolves correctly
char abs_secret[PATH_MAX];
ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
auto se = detail::scope_exit([&] {
unlink(symlink_path.c_str());
unlink(secret_file.c_str());
rmdir(served_dir.c_str());
rmdir(secret_dir.c_str());
});
Server svr;
svr.set_mount_point("/", served_dir);
auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
auto se2 = detail::scope_exit([&] {
svr.stop();
listen_thread.join();
});
svr.wait_until_ready();
Client cli("localhost", PORT);
// Symlink pointing outside base dir should be blocked
auto res = cli.Get("/escape/secret.txt");
ASSERT_TRUE(res);
EXPECT_EQ(StatusCode::Forbidden_403, res->status);
}
#endif
+9
View File
@@ -0,0 +1,9 @@
#include "../httplib.h"
int main() {
httplib::Server svr;
httplib::Client cli("localhost", 8080);
(void)svr;
(void)cli;
return 0;
}
+78
View File
@@ -0,0 +1,78 @@
#include <httplib.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <chrono>
#include <sstream>
#include <thread>
#include <vector>
using namespace httplib;
static const int PORT = 11134;
static void performance_test(const char *host) {
Server svr;
svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
res.set_content("Benchmark Response", "text/plain");
});
auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
auto se = detail::scope_exit([&] {
svr.stop();
listen_thread.join();
ASSERT_FALSE(svr.is_running());
});
svr.wait_until_ready();
Client cli(host, PORT);
// Warm-up request to establish connection and resolve DNS
auto warmup_res = cli.Get("/benchmark");
ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
// Run multiple trials and collect timings
const int num_trials = 20;
std::vector<int64_t> timings;
timings.reserve(num_trials);
for (int i = 0; i < num_trials; i++) {
auto start = std::chrono::high_resolution_clock::now();
auto res = cli.Get("/benchmark");
auto end = std::chrono::high_resolution_clock::now();
auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
.count();
// Assertions after timing measurement to avoid overhead
ASSERT_TRUE(res);
EXPECT_EQ(StatusCode::OK_200, res->status);
timings.push_back(elapsed);
}
// Calculate 25th percentile (lower quartile)
std::sort(timings.begin(), timings.end());
auto p25 = timings[num_trials / 4];
// Format timings for output
std::ostringstream timings_str;
timings_str << "[";
for (size_t i = 0; i < timings.size(); i++) {
if (i > 0) timings_str << ", ";
timings_str << timings[i];
}
timings_str << "]";
// Localhost HTTP GET should be fast even in CI environments
EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
<< "ms (Issue #1777). Timings: " << timings_str.str();
}
TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
TEST(BenchmarkTest, v6) { performance_test("::1"); }
+71
View File
@@ -109,6 +109,55 @@ TEST(RedirectTest, YouTubeSSLDigest) {
// ----------------------------------------------------------------------------
#ifdef CPPHTTPLIB_SSL_ENABLED
TEST(RedirectTest, TLSVerificationOnProxyRedirect) {
// Untrusted HTTPS server with self-signed cert
SSLServer untrusted_svr("cert.pem", "key.pem");
untrusted_svr.Get("/", [](const Request &, Response &res) {
res.set_content("MITM'd", "text/plain");
});
auto untrusted_port = untrusted_svr.bind_to_any_port("0.0.0.0");
auto t1 = thread([&]() { untrusted_svr.listen_after_bind(); });
auto se1 = detail::scope_exit([&] {
untrusted_svr.stop();
t1.join();
});
// HTTP server that redirects to the untrusted HTTPS server
// Use host.docker.internal so the proxy container can reach the host
Server redirect_svr;
redirect_svr.Get("/", [&](const Request &, Response &res) {
res.set_redirect(
"https://host.docker.internal:" + to_string(untrusted_port) + "/");
});
auto redirect_port = redirect_svr.bind_to_any_port("0.0.0.0");
auto t2 = thread([&]() { redirect_svr.listen_after_bind(); });
auto se2 = detail::scope_exit([&] {
redirect_svr.stop();
t2.join();
});
// Wait until servers are up
untrusted_svr.wait_until_ready();
redirect_svr.wait_until_ready();
// Client with proxy + follow_location, verification ON (default)
Client cli("host.docker.internal", redirect_port);
cli.set_proxy("localhost", 3128);
cli.set_proxy_basic_auth("hello", "world");
cli.set_follow_location(true);
auto res = cli.Get("/");
// Self-signed cert must be rejected
ASSERT_TRUE(res == nullptr);
}
#endif
// ----------------------------------------------------------------------------
template <typename T> void BaseAuthTestFromHTTPWatch(T &cli) {
cli.set_proxy("localhost", 3128);
cli.set_proxy_basic_auth("hello", "world");
@@ -295,3 +344,25 @@ TEST(KeepAliveTest, SSLWithDigest) {
KeepAliveTest(cli, false);
}
#endif
// ----------------------------------------------------------------------------
#ifdef CPPHTTPLIB_SSL_ENABLED
TEST(ProxyTest, SSLOpenStream) {
SSLClient cli("nghttp2.org");
cli.set_proxy("localhost", 3128);
cli.set_proxy_basic_auth("hello", "world");
auto handle = cli.open_stream("GET", "/httpbin/get");
ASSERT_TRUE(handle.response);
EXPECT_EQ(StatusCode::OK_200, handle.response->status);
std::string body;
char buf[8192];
ssize_t n;
while ((n = handle.read(buf, sizeof(buf))) > 0) {
body.append(buf, static_cast<size_t>(n));
}
EXPECT_FALSE(body.empty());
}
#endif
+79
View File
@@ -57,6 +57,85 @@ TEST_F(WebSocketHeartbeatTest, IdleConnectionStaysAlive) {
client.close();
}
// Verify that set_websocket_ping_interval overrides the compile-time default
TEST_F(WebSocketHeartbeatTest, RuntimePingIntervalOverride) {
// The server is already using the compile-time default (1s).
// Create a client with a custom runtime interval.
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
client.set_websocket_ping_interval(2);
ASSERT_TRUE(client.connect());
// Sleep longer than read timeout (3s). Client heartbeat at 2s keeps alive.
std::this_thread::sleep_for(std::chrono::seconds(5));
ASSERT_TRUE(client.is_open());
ASSERT_TRUE(client.send("runtime interval"));
std::string msg;
ASSERT_TRUE(client.read(msg));
EXPECT_EQ("runtime interval", msg);
client.close();
}
// Verify that ping_interval=0 disables heartbeat without breaking basic I/O.
TEST_F(WebSocketHeartbeatTest, ZeroDisablesHeartbeat) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
client.set_websocket_ping_interval(0);
ASSERT_TRUE(client.connect());
// Basic send/receive still works with heartbeat disabled
ASSERT_TRUE(client.send("no client ping"));
std::string msg;
ASSERT_TRUE(client.read(msg));
EXPECT_EQ("no client ping", msg);
client.close();
}
// Verify that Server::set_websocket_ping_interval works at runtime
class WebSocketServerPingIntervalTest : public ::testing::Test {
protected:
void SetUp() override {
svr_.set_websocket_ping_interval(2);
svr_.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
std::string msg;
while (ws.read(msg)) {
ws.send(msg);
}
});
port_ = svr_.bind_to_any_port("localhost");
thread_ = std::thread([this]() { svr_.listen_after_bind(); });
svr_.wait_until_ready();
}
void TearDown() override {
svr_.stop();
thread_.join();
}
Server svr_;
int port_;
std::thread thread_;
};
TEST_F(WebSocketServerPingIntervalTest, ServerRuntimeInterval) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
ASSERT_TRUE(client.connect());
// Server ping interval is 2s; client uses compile-time default (1s).
// Both keep the connection alive.
std::this_thread::sleep_for(std::chrono::seconds(5));
ASSERT_TRUE(client.is_open());
ASSERT_TRUE(client.send("server interval"));
std::string msg;
ASSERT_TRUE(client.read(msg));
EXPECT_EQ("server interval", msg);
client.close();
}
// Verify that multiple heartbeat cycles work
TEST_F(WebSocketHeartbeatTest, MultipleHeartbeatCycles) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");