### Basic cpp-httplib Server Setup Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Sets up a basic HTTP server with a simple GET endpoint. Include the httplib.h header to use the Server class. ```cpp #include int main(void) { using namespace httplib; Server svr; svr.Get("/hi", [](const Request& req, Response& res) { res.set_content("Hello World!", "text/plain"); }); // Match the request path against a regular expression // and extract its captures svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) { auto numbers = req.matches[1]; res.set_content(numbers, "text/plain"); }); // Capture the second segment of the request path as "id" path param svr.Get("/users/:id", [&](const Request& req, Response& res) { auto user_id = req.path_params.at("id"); res.set_content(user_id, "text/plain"); }); // Extract values from HTTP headers and URL query params svr.Get("/body-header-param", [](const Request& req, Response& res) { if (req.has_header("Content-Length")) { auto val = req.get_header_value("Content-Length"); } if (req.has_param("key")) { auto val = req.get_param_value("key"); } res.set_content(req.body, "text/plain"); }); // If the handler takes time to finish, you can also poll the connection state svr.Get("/task", [&](const Request& req, Response& res) { const char * result = nullptr; process.run(); // for example, starting an external process while (result == nullptr) { sleep(1); if (req.is_connection_closed()) { process.kill(); // kill the process return; } result = process.stdout(); // != nullptr if the process finishes } res.set_content(result, "text/plain"); }); svr.Get("/stop", [&](const Request& req, Response& res) { svr.stop(); }); svr.listen("localhost", 1234); } ``` -------------------------------- ### Run a program with the default Crashpad handler Source: https://github.com/crashpad/crashpad/blob/main/tools/run_with_crashpad.md This example demonstrates starting the default crashpad_handler and running a program named 'crasher'. The --database option specifies the location for crash dumps. ```bash $ run_with_crashpad --database=/tmp/crashpad_database crasher Illegal instruction: 4 ``` -------------------------------- ### Server Basic Route Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md A simple example of setting up a GET route on the server that responds with plain text. ```APIDOC ## Server Basic Route ```cpp #include int main(void) { using namespace httplib; Server svr; svr.Get("/hi", [](const Request& req, Response& res) { res.set_content("Hello World!", "text/plain"); }); // ... other routes ... svr.listen("localhost", 1234); } ``` ``` -------------------------------- ### Bind to Any Port Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Demonstrates how to bind the server to a specific IP address and any available port, then start listening. ```APIDOC ## Bind a socket to multiple interfaces and any available port ```cpp int port = svr.bind_to_any_port("0.0.0.0"); svr.listen_after_bind(); ``` ``` -------------------------------- ### Server Route Accessing Headers and Query Params Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md An example of a GET route that demonstrates how to access HTTP headers and URL query parameters. ```APIDOC ## Server Route Accessing Headers and Query Params ```cpp #include int main(void) { using namespace httplib; Server svr; // Extract values from HTTP headers and URL query params svr.Get("/body-header-param", [](const Request& req, Response& res) { if (req.has_header("Content-Length")) { auto val = req.get_header_value("Content-Length"); } if (req.has_param("key")) { auto val = req.get_param_value("key"); } res.set_content(req.body, "text/plain"); }); // ... other routes ... svr.listen("localhost", 1234); } ``` ``` -------------------------------- ### C++ HTTP Server Example Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Demonstrates setting up a basic multi-threaded HTTP server. Ensure httplib.h is included and the necessary SSL support macro is defined if using HTTPS. ```cpp #define CPPHTTPLIB_OPENSSL_SUPPORT #include "path/to/httplib.h" // HTTP httplib::Server svr; // HTTPS httplib::SSLServer svr; svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) { res.set_content("Hello World!", "text/plain"); }); svr.listen("0.0.0.0", 8080); ``` -------------------------------- ### C++ HTTP Client Example Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Shows how to create an HTTP or HTTPS client to make requests. The client can be initialized with a URL or host. The response status and body can be accessed. ```cpp #define CPPHTTPLIB_OPENSSL_SUPPORT #include "path/to/httplib.h" // HTTP httplib::Client cli("http://yhirose.github.io"); // HTTPS httplib::Client cli("https://yhirose.github.io"); auto res = cli.Get("/hi"); res->status; res->body; ``` -------------------------------- ### Basic HTTP Client Usage Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Connect to a local server and make a GET request. Handles successful responses and logs HTTP errors. ```cpp #include #include int main(void) { httplib::Client cli("localhost", 1234); if (auto res = cli.Get("/hi")) { if (res->status == StatusCode::OK_200) { std::cout << res->body << std::endl; } } else { auto err = res.error(); std::cout << "HTTP error: " << httplib::to_string(err) << std::endl; } } ``` -------------------------------- ### C++ SSL Server and Client Setup Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Illustrates how to configure SSL for both server and client operations. This requires defining CPPHTTPLIB_OPENSSL_SUPPORT and linking against OpenSSL libraries. Server requires certificate and key paths, while clients can specify CA bundles, disable certificate verification, or hostname verification. ```cpp #define CPPHTTPLIB_OPENSSL_SUPPORT #include "path/to/httplib.h" // Server httplib::SSLServer svr("./cert.pem", "./key.pem"); // Client httplib::Client cli("https://localhost:1234"); // scheme + host httplib::SSLClient cli("localhost:1234"); // host httplib::SSLClient cli("localhost", 1234); // host, port // Use your CA bundle cli.set_ca_cert_path("./ca-bundle.crt"); // Disable cert verification cli.enable_server_certificate_verification(false); // Disable host verification cli.enable_server_hostname_verification(false); ``` -------------------------------- ### Run an on-demand exception server with launchd Source: https://github.com/crashpad/crashpad/blob/main/tools/mac/catch_exception_tool.md This example demonstrates setting up an on-demand exception server using launchd. The tool is loaded via `on_demand_service_tool`, configured to be persistent and with a zero timeout, meaning it runs until explicitly unloaded. Exceptions are written to `/tmp/out`. ```bash $ `on_demand_service_tool --load --label=catch_exception \ --mach-service=svc \ $(which catch_exception_tool) --mach-service=svc \ --file=/tmp/out --persistent --timeout=0 ``` ```bash $ exception_port_tool --set-handler=handler=bootstrap:svc crasher ``` ```bash $ on_demand_service_tool --unload --label=catch_exception ``` ```bash $ cat /tmp/out ``` -------------------------------- ### Run a program with a custom Crashpad handler and show exception ports Source: https://github.com/crashpad/crashpad/blob/main/tools/run_with_crashpad.md This example shows how to specify a custom path for the crashpad_handler executable using the --handler option. It then runs 'exception_port_tool' to display task-level exception port information, including the handler's configuration. ```bash $ run_with_crashpad --handler=/tmp/crashpad_handler \ --database=/tmp/crashpad_database exception_port_tool \ --show-task task exception port 0, mask 0x1c00 (CRASH|RESOURCE|GUARD), port 0x30b, behavior 0x80000003 (STATE_IDENTITY|MACH), flavor 7 (THREAD) ``` -------------------------------- ### Configure Crashpad for Fuchsia with Multiple Targets Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md When developing for multiple targets, include them in the target_os list in .gclient. For example, to target both Fuchsia and Mac. ```bash target_os=["fuchsia", "mac"] ``` -------------------------------- ### OPTIONS Request Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Illustrates how to send an OPTIONS request to get communication options for a target resource. ```APIDOC ## OPTIONS ### Description Sends an OPTIONS request to retrieve communication options for a target resource. ### Method OPTIONS ### Endpoint * or /resource/foo ### Request Example ```cpp res = cli.Options("* "); res = cli.Options("/resource/foo"); ``` ``` -------------------------------- ### GET /content Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Serves static file content directly from the filesystem. You can specify the file path and optionally the content type. ```APIDOC ## GET /content ### Description Serves the content of a specified file. The server reads the file from the given path and sends its content as the response. ### Method GET ### Endpoint /content ### Parameters None explicitly documented for the endpoint itself, but the `set_file_content` function takes the file path and optional content type. ### Request Example (with inferred content type) ```cpp svr.Get("/content", [&](const Request &req, Response &res) { res.set_file_content("./path/to/content.html"); }); ``` ### Request Example (with specified content type) ```cpp svr.Get("/content", [&](const Request &req, Response &res) { res.set_file_content("./path/to/content", "text/html"); }); ``` ``` -------------------------------- ### Run a one-shot blocking exception server Source: https://github.com/crashpad/crashpad/blob/main/tools/mac/catch_exception_tool.md This example shows how to run catch_exception_tool as a one-shot blocking server. Exceptions are logged to the specified file, and the tool exits after the first exception is caught. It is registered with the bootstrap server under the name 'svc'. ```bash $ catch_exception_tool --mach-service=svc --file=out & ``` ```bash $ exception_port_tool --set-handler=handler=bootstrap:svc crasher ``` ```bash $ cat out ``` -------------------------------- ### Server Route with Path Parameter Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Sets up a GET route that extracts a named path parameter from the URL. ```APIDOC ## Server Route with Path Parameter ```cpp #include int main(void) { using namespace httplib; Server svr; // Capture the second segment of the request path as "id" path param svr.Get("/users/:id", [&](const Request& req, Response& res) { auto user_id = req.path_params.at("id"); res.set_content(user_id, "text/plain"); }); // ... other routes ... svr.listen("localhost", 1234); } ``` ``` -------------------------------- ### GET Request with Custom HTTP Headers Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Send a GET request with custom headers. Supports defining headers individually or setting default headers for the client. ```cpp httplib::Headers headers = { { "Hello", "World!" } }; auto res = cli.Get("/hi", headers); ``` ```cpp auto res = cli.Get("/hi", {{"Hello", "World!"}}); ``` ```cpp cli.set_default_headers({ { "Hello", "World!" } }); auto res = cli.Get("/hi"); ``` -------------------------------- ### Receive Content with Response Callback Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Process response content using a callback that receives data in chunks. This example also demonstrates handling the initial response headers and status code. The callback can return `false` to cancel the request. ```c++ std::string body; auto res = cli.Get( "/stream", Headers(), [&](const Response &response) { EXPECT_EQ(StatusCode::OK_200, response.status); return true; // return 'false' if you want to cancel the request. }, [&](const char *data, size_t data_length) { body.append(data, data_length); return true; // return 'false' if you want to cancel the request. }); ``` -------------------------------- ### Bind Server Socket to Any Port Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Binds the server socket to a specified IP address ('0.0.0.0' for all interfaces) and any available port, then starts listening. This is useful when the port needs to be dynamically assigned. ```cpp int port = svr.bind_to_any_port("0.0.0.0"); svr.listen_after_bind(); ``` -------------------------------- ### Disable and Verify Report Uploads Source: https://github.com/crashpad/crashpad/blob/main/tools/crashpad_database_util.md This example demonstrates disabling report uploads in a crash report database's settings and then verifying the change. It first sets the upload status to 'false' and then queries the status to confirm. ```bash $ crashpad_database_util --database /tmp/crashpad_database \ --set-uploads-enabled false $ crashpad_database_util --database /tmp/crashpad_database \ --show-uploads-enabled false ``` -------------------------------- ### Server Stop Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Provides a simple GET route to gracefully stop the HTTP server. ```APIDOC ## Server Stop ```cpp #include int main(void) { using namespace httplib; Server svr; svr.Get("/stop", [&](const Request& req, Response& res) { svr.stop(); }); // ... other routes ... svr.listen("localhost", 1234); } ``` ``` -------------------------------- ### Initial Crashpad Source Code Checkout Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Use fetch and gclient to perform the initial clone and sync for a fully functional local checkout of Crashpad. ```bash $ mkdir ~/crashpad $ cd ~/crashpad $ fetch crashpad ``` -------------------------------- ### Configure and Build for Fuchsia Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Generate build files for Fuchsia and build the project. Ensure you have a connected Fuchsia device for testing. ```bash $ gn gen out/fuchsia --args 'target_os="fuchsia" target_cpu="x64" is_debug=true' $ ninja -C out/fuchsia $ python build/run_tests.py out/fuchsia ``` -------------------------------- ### Server Route with Regex Capture Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Defines a GET route that uses a regular expression to capture a part of the URL path. ```APIDOC ## Server Route with Regex Capture ```cpp #include int main(void) { using namespace httplib; Server svr; // Match the request path against a regular expression // and extract its captures svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) { auto numbers = req.matches[1]; res.set_content(numbers, "text/plain"); }); // ... other routes ... svr.listen("localhost", 1234); } ``` ``` -------------------------------- ### HTTP Client Constructor Overloads Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Demonstrates various ways to construct an httplib::Client object using different URI formats and schemes. ```cpp httplib::Client cli("localhost"); httplib::Client cli("localhost:8080"); httplib::Client cli("http://localhost"); httplib::Client cli("http://localhost:8080"); httplib::Client cli("https://localhost"); httplib::SSLClient cli("localhost"); ``` -------------------------------- ### Configure Fuchsia Target OS for gclient Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Add target_os to .gclient to instruct gclient to download the Fuchsia SDK. This is necessary for building Crashpad for Fuchsia. ```bash target_os=["fuchsia"] ``` -------------------------------- ### Unregister an on-demand Mach service Source: https://github.com/crashpad/crashpad/blob/main/tools/mac/on_demand_service_tool.md Unregisters an on-demand server previously installed with --load. The label used during registration is required for unregistration. ```bash $ on_demand_service_tool --unload --label=catch_exception ``` -------------------------------- ### Optional Linux Build Configuration: Fetching Clang and Sysroot Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Configure Crashpad's .gclient file to pull Crashpad's version of clang and sysroot for Linux builds. ```bash "custom_vars": { "pull_linux_clang": True }, ``` -------------------------------- ### Range Requests Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Specify a byte range for a GET request using `httplib::make_range_header`. The server should respond with status code 206 if the range is supported. ```c++ httplib::Client cli("httpbin.org"); auto res = cli.Get("/range/32", { httplib::make_range_header({{1, 10}}) // 'Range: bytes=1-10' }); // res->status should be 206. // res->body should be "bcdefghijk". ``` ```c++ httplib::make_range_header({{1, 10}, {20, -1}}) // 'Range: bytes=1-10, 20-' httplib::make_range_header({{100, 199}, {500, 599}}) // 'Range: bytes=100-199, 500-599' httplib::make_range_header({{0, 0}, {-1, 1}}) // 'Range: bytes=0-0, -1' ``` -------------------------------- ### Build Crashpad with GN and Ninja Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Generate Ninja build files using GN and then build Crashpad. This is the standard procedure for Windows, Mac, Linux, and Fuchsia. ```bash $ cd ~/crashpad/crashpad $ gn gen out/Default $ ninja -C out/Default ``` -------------------------------- ### GET /stream Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Provides content via a streaming mechanism, allowing data to be sent in chunks. This is useful for large responses or dynamically generated content. ```APIDOC ## GET /stream ### Description Sends content dynamically generated or streamed in chunks. This method is suitable for large data transfers or when the entire content is not available upfront. ### Method GET ### Endpoint /stream ### Parameters None explicitly documented for the endpoint itself, but the `set_content_provider` function takes callbacks for data provision. ### Response #### Success Response (200) - **Content** (stream) - Dynamically provided data chunks. ### Request Example (with content length) ```cpp svr.Get("/stream", [&](const Request &req, Response &res) { auto data = new std::string("abcdefg"); res.set_content_provider( data->size(), // Content length "text/plain", // Content type [&, data](size_t offset, size_t length, DataSink &sink) { const auto &d = *data; sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE)); return true; }, [data](bool success) { delete data; }); }); ``` ### Request Example (without content length) ```cpp svr.Get("/stream", [&](const Request &req, Response &res) { res.set_content_provider( "text/plain", // Content type [&](size_t offset, DataSink &sink) { if (/* there is still data */) { std::vector data; // prepare data... sink.write(data.data(), data.size()); } else { sink.done(); // No more data } return true; }); }); ``` ``` -------------------------------- ### Filter Crashpad Tests Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Run a subset of tests using the --gtest_filter flag with the test runner script. This example filters for tests related to MinidumpStringWriter. ```bash $ python build/run_tests.py out/Debug --gtest_filter MinidumpStringWriter\* ``` -------------------------------- ### Build and Run cpp-httplib Docker Server Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Instructions for building a Docker image for a static HTTP server using cpp-httplib and running it. It serves files from /html on port 80, and is exposed on port 8080. ```bash > docker build -t cpp-httplib-server . ... > docker run --rm -it -p 8080:80 -v ./docker/html:/html cpp-httplib-server Serving HTTP on 0.0.0.0 port 80 ... 192.168.65.1 - - [31/Aug/2024:21:33:56 +0000] "GET / HTTP/1.1" 200 599 "-" "curl/8.7.1" 192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET / HTTP/1.1" 200 599 "-" "Mozilla/5.0 ..." 192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..." ``` ```bash > docker run --rm -it -p 8080:80 -v ./docker/html:/html yhirose4dockerhub/cpp-httplib-server Serving HTTP on 0.0.0.0 port 80 ... 192.168.65.1 - - [31/Aug/2024:21:33:56 +0000] "GET / HTTP/1.1" 200 599 "-" "curl/8.7.1" 192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET / HTTP/1.1" 200 599 "-" "Mozilla/5.0 ..." 192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..." ``` -------------------------------- ### Windows Header Inclusion Order Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Illustrates the correct order for including httplib.h and Windows.h on Windows to avoid conflicts. Define WIN32_LEAN_AND_MEAN before including Windows.h if necessary. ```cpp #include #include ``` ```cpp #define WIN32_LEAN_AND_MEAN #include #include ``` -------------------------------- ### GET /chunked Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Implements chunked transfer encoding, allowing the server to send data in discrete chunks without knowing the total size beforehand. Supports trailers for additional metadata. ```APIDOC ## GET /chunked ### Description Sends content using chunked transfer encoding. This allows for sending data in pieces, which is useful when the total size is unknown or when data is generated incrementally. It also supports adding trailers to the response. ### Method GET ### Endpoint /chunked ### Parameters None explicitly documented for the endpoint itself, but the `set_chunked_content_provider` function takes callbacks for data provision. ### Response #### Success Response (200) - **Content** (stream) - Data sent in chunks. ### Request Example (without trailer) ```cpp svr.Get("/chunked", [&](const Request& req, Response& res) { res.set_chunked_content_provider( "text/plain", [](size_t offset, DataSink &sink) { sink.write("123", 3); sink.write("345", 3); sink.write("789", 3); sink.done(); // No more data return true; } ); }); ``` ### Request Example (with trailer) ```cpp svr.Get("/chunked", [&](const Request& req, Response& res) { res.set_header("Trailer", "Dummy1, Dummy2"); res.set_chunked_content_provider( "text/plain", [](size_t offset, DataSink &sink) { sink.write("123", 3); sink.write("345", 3); sink.write("789", 3); sink.done_with_trailer({ {"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"} }); return true; } ); }); ``` ``` -------------------------------- ### Mounting Static Files Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Configure the server to serve static files from specified directories. Multiple directories can be mounted to the same path, with the server searching them in the order they are added. Use `remove_mount_point` to unmount. ```cpp // Mount / to ./www directory auto ret = svr.set_mount_point("/", "./www"); if (!ret) { // The specified base directory doesn't exist... } // Mount /public to ./www directory ret = svr.set_mount_point("/public", "./www"); // Mount /public to ./www1 and ./www2 directories ret = svr.set_mount_point("/public", "./www1"); // 1st order to search ret = svr.set_mount_point("/public", "./www2"); // 2nd order to search // Remove mount / ret = svr.remove_mount_point("/"); // Remove mount /public ret = svr.remove_mount_point("/public"); ``` -------------------------------- ### Static File Server Configuration Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Configure the static file server to serve files from specified directories. Multiple directories can be mounted to the same path, with the first one listed taking precedence. ```APIDOC ## Static File Server Configuration ### Description Mounts a directory to a specific path for serving static files. If multiple directories are mounted to the same path, they are searched in the order they were added. ### Methods - `set_mount_point(const char* mount_point, const char* dir)`: Mounts a directory to a given path. - `remove_mount_point(const char* mount_point)`: Removes a mount point. ### Example Usage ```cpp // Mount / to ./www directory auto ret = svr.set_mount_point("/", "./www"); // Mount /public to ./www directory ret = svr.set_mount_point("/public", "./www"); // Mount /public to ./www1 and ./www2 directories (order matters) ret = svr.set_mount_point("/public", "./www1"); // 1st order to search ret = svr.set_mount_point("/public", "./www2"); // 2nd order to search // Remove mount / ret = svr.remove_mount_point("/"); // Remove mount /public ret = svr.remove_mount_point("/public"); ``` ### Warning These static file server methods are not thread-safe. ``` -------------------------------- ### Proxy Server Configuration Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Set up a proxy server for HTTP requests, including authentication options for the proxy. Digest authentication for the proxy also requires OpenSSL. ```c++ cli.set_proxy("host", port); // Basic Authentication cli.set_proxy_basic_auth("user", "pass"); // Digest Authentication cli.set_proxy_digest_auth("user", "pass"); // Bearer Token Authentication cli.set_proxy_bearer_token_auth("pass"); ``` -------------------------------- ### Split httplib.h Script Usage Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Demonstrates how to use the split.py script to separate httplib.h into .h and .cc files. Specify extension and output directory if needed. ```console $ ./split.py -h usage: split.py [-h] [-e EXTENSION] [-o OUT] This script splits httplib.h into .h and .cc parts. optional arguments: -h, --help show this help message and exit -e EXTENSION, --extension EXTENSION extension of the implementation file (default: cc) -o OUT, --out OUT where to write the files (default: out) $ ./split.py Wrote out/httplib.h and out/httplib.cc ``` -------------------------------- ### Optional Linux Build Configuration: GN Args for Clang and Sysroot Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Add these GN arguments to out/Default/args.gn to specify the paths for the fetched clang and sysroot when building on Linux. ```bash clang_path = "//third_party/linux/clang/linux-amd64" target_sysroot = "//third_party/linux/sysroot" ``` -------------------------------- ### Run All Crashpad Tests Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Use the provided script to run all unit tests. Specify the directory containing the test executables as an argument. ```bash $ cd ~/crashpad/crashpad $ python build/run_tests.py out/Debug ``` -------------------------------- ### Android Build Configuration: Set Target OS and NDK Root Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Configure GN arguments for Android builds by setting target_os to 'android' and specifying the android_ndk_root path. ```bash target_os = "android" android_ndk_root = ~/android-ndk ``` -------------------------------- ### HTML form equivalent for crashpad_http_upload Source: https://github.com/crashpad/crashpad/blob/main/tools/crashpad_http_upload.md This HTML form demonstrates the equivalent of the crashpad_http_upload command, showing how text inputs and file inputs map to the command-line options. ```html
``` -------------------------------- ### Run Crashpad Unit Tests Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md Execute individual test executables after building. These are typically found in the 'out/Debug' directory. ```bash $ cd ~/crashpad/crashpad $ out/Debug/crashpad_minidump_test $ out/Debug/crashpad_util_test ``` -------------------------------- ### Local Connection Performance Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md For local connections on Windows, use "127.0.0.1" instead of "localhost" to avoid potential DNS resolution delays. ```cpp // May be slower on Windows due to DNS resolution delays httplib::Client cli("localhost", 8080); httplib::Server svr; svr.listen("localhost", 8080); // Faster alternative for local connections httplib::Client cli("127.0.0.1", 8080); httplib::Server svr; svr.listen("127.0.0.1", 8080); ``` -------------------------------- ### Progress Callback for Downloads Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Monitor download progress by providing a callback function that is invoked with the number of bytes received and the total expected size. Returning `false` from the callback cancels the download. ```c++ httplib::Client cli(url, port); // prints: 0 / 000 bytes => 50% complete auto res = cli.Get("/", [](size_t len, size_t total) { printf("%lld / %lld bytes => %d%% complete\n", len, total, (int)(len*100/total)); return true; // return 'false' if you want to cancel the request. } ); ``` -------------------------------- ### Timeout Settings Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Explains how to configure connection, read, write, and maximum timeouts for client requests. ```APIDOC ## Timeout Configuration ### Description Allows setting various timeout durations for client operations. ### Methods - `set_connection_timeout(seconds, microseconds)`: Sets the timeout for establishing a connection. - `set_read_timeout(seconds, microseconds)`: Sets the timeout for reading data from the connection. - `set_write_timeout(seconds, microseconds)`: Sets the timeout for writing data to the connection. - `set_max_timeout(milliseconds)`: Sets the maximum time allowed for the entire request, similar to `curl --max-time`. ### Example ```cpp cli.set_connection_timeout(0, 300000); // 300 milliseconds cli.set_read_timeout(5, 0); // 5 seconds cli.set_write_timeout(5, 0); // 5 seconds cli.set_max_timeout(5000); // 5 seconds ``` ``` -------------------------------- ### Client Access Logging Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Set up a custom logger for client requests and responses to track request details, status codes, body size, and latency. ```cpp cli.set_logger([](const httplib::Request& req, const httplib::Response& res) { auto duration = std::chrono::duration_cast( std::chrono::steady_clock::now() - start_time).count(); std::cout << "✓ " << req.method << " " << req.path << " -> " << res.status << " (" << res.body.size() << " bytes, " << duration << "ms)" << std::endl; }); ``` -------------------------------- ### Subsequent Crashpad Source Code Updates Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md After the initial checkout, use git pull and gclient sync for subsequent updates to the Crashpad source code. ```bash $ cd ~/crashpad/crashpad $ git pull -r $ gclient sync ``` -------------------------------- ### Range Requests Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Demonstrates how to make range requests to fetch partial content of a resource. ```APIDOC ## GET /range/32 with Range Header ### Description Fetches a specific byte range of a resource. ### Method GET ### Endpoint /range/32 ### Headers - **Range**: Specifies the byte range(s) to retrieve. ### Request Example ```cpp httplib::Client cli("httpbin.org"); auto res = cli.Get("/range/32", { httplib::make_range_header({{1, 10}}) // 'Range: bytes=1-10' }); // res->status should be 206. // res->body should be "bcdefghijk". ``` ### Helper Function for Range Header - `httplib::make_range_header(ranges)`: Creates a `Range` header value from a vector of range specifications. ### Range Specification Examples - `{{1, 10}}`: `bytes=1-10` - `{{1, 10}, {20, -1}}`: `bytes=1-10, 20-` - `{{100, 199}, {500, 599}}`: `bytes=100-199, 500-599` - `{{0, 0}, {-1, 1}}`: `bytes=0-0, -1` ``` -------------------------------- ### Access Logging Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Set up an access logger to capture details of successful HTTP requests and responses. The logger receives the request method, path, and response status. ```cpp svr.set_logger([](const httplib::Request& req, const httplib::Response& res) { std::cout << req.method << " " << req.path << " -> " << res.status << std::endl; }); ``` -------------------------------- ### Upload Patch for Code Review Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md This command sequence is used to prepare and upload a local Git branch for code review on Gerrit. Ensure you are in the crashpad directory and have made your changes. ```bash cd ~/crashpad/crashpad git checkout -b work_branch origin/main …do some work… git add … git commit git cl upload ``` -------------------------------- ### OPTIONS Request Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Send an OPTIONS request to query the communication options for a resource or the server. ```c++ res = cli.Options("*\n"); res = cli.Options("/resource/foo"); ``` -------------------------------- ### Upload a file and string to an HTTP server Source: https://github.com/crashpad/crashpad/blob/main/tools/crashpad_http_upload.md Use this command to upload a file and a string value to a specified URL. The file is sent as a file upload, and the string is sent as an ordinary form field. ```bash $ crashpad_http-upload --url http://localhost/upload_test \ --string=when=now --file=what=1040.pdf Thanks for the upload! ``` -------------------------------- ### URI Encoding and Decoding Utilities Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Utilize `encode_uri`, `decode_uri`, `encode_uri_component`, and `decode_uri_component` for proper URI handling. ```cpp #include std::string url = "https://example.com/search?q=hello world"; std::string encoded = httplib::encode_uri(url); std::string decoded = httplib::decode_uri(encoded); std::string param = "hello world"; std::string encoded_component = httplib::encode_uri_component(param); std::string decoded_component = httplib::decode_uri_component(encoded_component); ``` -------------------------------- ### Pre-compression Logging Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Configure a logger to capture request and response data before any compression is applied. This logger is only called for responses where compression would be used. ```cpp svr.set_pre_compression_logger([](const httplib::Request& req, const httplib::Response& res) { // Log before compression - res.body contains uncompressed content // Content-Encoding header is not yet set your_pre_compression_logger(req, res); }); ``` -------------------------------- ### POST Request with Parameters Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Send POST requests using the httplib::Params type for key-value pairs, suitable for form submissions. ```cpp httplib::Params params; params.emplace("name", "john"); params.emplace("note", "coder"); auto res = cli.Post("/post", params); ``` ```cpp httplib::Params params{ { "name", "john" }, { "note", "coder" } }; auto res = cli.Post("/post", params); ``` -------------------------------- ### Handle SSL Errors in cpp-httplib Client Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Demonstrates how to check for and interpret various SSL-related errors when making HTTPS requests. Ensure CPPHTTPLIB_OPENSSL_SUPPORT is defined. ```cpp #define CPPHTTPLIB_OPENSSL_SUPPORT #include "path/to/httplib.h" httplib::Client cli("https://example.com"); auto res = cli.Get("/"); if (!res) { // Check the error type const auto err = res.error(); switch (err) { case httplib::Error::SSLConnection: std::cout << "SSL connection failed, SSL error: " << res.ssl_error() << std::endl; break; case httplib::Error::SSLLoadingCerts: std::cout << "SSL cert loading failed, OpenSSL error: " << std::hex << res.ssl_openssl_error() << std::endl; break; case httplib::Error::SSLServerVerification: std::cout << "SSL verification failed, X509 error: " << res.ssl_openssl_error() << std::endl; break; case httplib::Error::SSLServerHostnameVerification: std::cout << "SSL hostname verification failed, X509 error: " << res.ssl_openssl_error() << std::endl; break; default: std::cout << "HTTP error: " << httplib::to_string(err) << std::endl; } } ``` -------------------------------- ### Unix Domain Socket Server and Client Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Configure both server and client to use Unix domain sockets for communication. Ensure correct file permissions for the socket path. ```cpp // Server httplib::Server svr; svr.set_address_family(AF_UNIX).listen("./my-socket.sock", 80); // Client httplib::Client cli("./my-socket.sock"); cli.set_address_family(AF_UNIX); ``` -------------------------------- ### Set 'Expect: 100-continue' handler to return 417 Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Configures the server to respond with a '417 Expectation Failed' status when an 'Expect: 100-continue' header is received. ```cpp // Send a '417 Expectation Failed' response. svr.set_expect_100_continue_handler([](const Request &req, Response &res) { return StatusCode::ExpectationFailed_417; }); ``` -------------------------------- ### Set read, write, and idle timeouts Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Configures the read timeout, write timeout, and idle interval for server connections. ```c++ svr.set_read_timeout(5, 0); // 5 seconds svr.set_write_timeout(5, 0); // 5 seconds svr.set_idle_interval(0, 100000); // 100 milliseconds ``` -------------------------------- ### Server Route for Long-Running Tasks Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Illustrates how to handle requests for tasks that might take time to complete, including checking for connection closure and polling for results. ```APIDOC ## Server Route for Long-Running Tasks ```cpp #include int main(void) { using namespace httplib; Server svr; // If the handler takes time to finish, you can also poll the connection state svr.Get("/task", [&](const Request& req, Response& res) { const char * result = nullptr; process.run(); // for example, starting an external process while (result == nullptr) { sleep(1); if (req.is_connection_closed()) { process.kill(); // kill the process return; } result = process.stdout(); // != nullptr if the process finishes } res.set_content(result, "text/plain"); }); // ... other routes ... svr.listen("localhost", 1234); } ``` ``` -------------------------------- ### Specify Fuchsia Device for Testing Source: https://github.com/crashpad/crashpad/blob/main/doc/developing.md When multiple Fuchsia devices are running, specify the target device using the ZIRCON_NODENAME environment variable with the test runner script. ```bash $ ZIRCON_NODENAME=scare-brook-skip-dried python build/run_tests.py out/fuchsia ``` -------------------------------- ### Send content with a content provider (with length) Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Provides content for a response using a data provider, specifying the content length and type. The data is written in chunks. ```cpp const size_t DATA_CHUNK_SIZE = 4; svr.Get("/stream", [&](const Request &req, Response &res) { auto data = new std::string("abcdefg"); res.set_content_provider( data->size(), // Content length "text/plain", // Content type [&, data](size_t offset, size_t length, DataSink &sink) { const auto &d = *data; sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE)); return true; // return 'false' if you want to cancel the process. }, [data](bool success) { delete data; }); }); ``` -------------------------------- ### Redirect Handling Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md Configure the client to automatically follow HTTP redirects. By default, redirects are not followed, and the response status code will indicate the redirect (e.g., 301). ```c++ httplib::Client cli("yahoo.com"); auto res = cli.Get("/"); res->status; // 301 cli.set_follow_location(true); res = cli.Get("/"); res->status; // 200 ``` -------------------------------- ### Default Accept-Encoding Source: https://github.com/crashpad/crashpad/blob/main/third_party/cpp-httplib/cpp-httplib/README.md The default `Accept-Encoding` header includes all supported compression types. Set to an empty string to request no compression. ```c++ res = cli.Get("/resource/foo"); res = cli.Get("/resource/foo", {{"Accept-Encoding", "br, gzip, deflate, zstd"}}); res = cli.Get("/resource/foo", {{"Accept-Encoding", ""}}); ```