HTTP(S) Server & Endpoints
Relevant source files
The following files were used as context for generating this wiki page:
The HttpServer component provides a high-performance, C++20 coroutine-based framework for building networked applications. It supports both standard HTTP and encrypted HTTPS protocols, enabling developers to define endpoints, handle file transfers, and implement WebSocket communications using a declarative API.
The system utilizes an asynchronous I/O model to manage connections efficiently. It allows for the registration of routes mapped to specific HTTP methods and provides Aspect-Oriented Programming (AOP) capabilities through "before" and "after" hooks for request processing.
Sources: examples/Server/01_http_server.cpp:78-83, include/HXLibs/net/protocol/http/Response.hpp:332-340
Server Architecture and Lifecycle
The HttpServer manages the network lifecycle, including socket binding, worker thread management, and request dispatching. You initialize the server by providing a port number and start it using either synchronous or asynchronous run methods.
Core Server Methods
| Method | Description |
|---|---|
syncRun(workers) | Starts the server and blocks the current thread, using the specified number of worker threads. |
asyncRun(workers) | Starts the server in a non-blocking manner. |
asyncStop() | Initiates a graceful shutdown of the server. |
addEndpoint<Method>(path, handler, ...aops) | Registers a new route with a specific HTTP method and optional AOP interceptors. |
addController<T>() | Registers a controller class containing multiple endpoint definitions. |
Sources: examples/Server/01_http_server.cpp:78-129, tests/server/01_http_server.cpp:44-67, tests/net/net_server.cpp:115-120
Connection Flow Diagram
The following diagram illustrates how the server handles an incoming request and routes it to a defined endpoint.
The diagram shows the sequence from socket acceptance to response transmission, including AOP hooks and connection persistence logic.
Sources: include/HXLibs/net/protocol/http/Response.hpp:144-180, examples/Server/01_http_server.cpp:21-40
Endpoint Definition and Routing
Endpoints are defined using the addEndpoint method, which supports various HTTP methods and path patterns, including wildcards and path parameters.
Supported HTTP Methods
The library defines methods within the HttpMethod enum:
GET,POST,PUT,DEL(DELETE),HEAD,PATCH,OPTIONS,TRACE.WSis an alias forGET, specifically used for WebSocket upgrades.
Sources: include/HXLibs/net/protocol/http/Http.hpp:95-107
Path Patterns and Parameters
Routing supports dynamic segments and wildcards:
- Static Paths: Exact matches like
/. - Path Parameters: Defined using braces, e.g.,
/api/users/{userId}. Parameters are retrieved viareq.getPathParam(index). - Universal Wildcards: Defined using
**, e.g.,/files/**. The wildcard path is retrieved viareq.getUniversalWildcardPath().
Sources: benchmarks/http/servers/hxlibs_server.cpp:64-70, examples/Server/01_http_server.cpp:101-105, tests/net/net_server.cpp:323-330
Aspect-Oriented Programming (AOP)
You can inject logic before and after handlers by passing structures with before and after methods to addEndpoint.
struct TimeLog {
auto before(Request&, Response&) {
t = std::chrono::steady_clock::now();
return ServerStatus::Ok;
}
auto after(Request& req, Response&) {
// Log duration logic
return true;
}
};
Sources: examples/Server/01_http_server.cpp:21-40, tests/server/01_http_server.cpp:21-34
Data Transfer and File Handling
HttpResponse provides specialized methods for efficient data transfer, including large file handling and streaming.
Transfer Strategies
| Strategy | Method | Description |
|---|---|---|
| Standard | setStatusAndContent | Sends a status code and a complete memory-buffered body. |
| Chunked | useChunkedEncodingTransferFile | Uses Transfer-Encoding: chunked to send files in pieces without a pre-calculated Content-Length. |
| Range | useRangeTransferFile | Supports Range requests for partial content (206) and resume-able downloads. |
| SSE | makeSseStream | Initiates a Server-Sent Events stream for real-time data pushing. |
Sources: include/HXLibs/net/protocol/http/Response.hpp:332-550, examples/Server/02_https_server.cpp:33-40
Range Transfer Logic
When useRangeTransferFile is called, the server checks the Range header in the HttpRequest. If a range is specified, the server calculates the byte offsets, sets the Content-Range header, and transmits only the requested segments. If no range is present, it defaults to a full file transfer.
Sources: include/HXLibs/net/protocol/http/Response.hpp:415-440, examples/Server/01_http_server.cpp:108-115
HTTPS Configuration
To enable HTTPS, the server must be initialized with an SSL context. This involves providing certificate and private key paths.
#ifdef HXLIBS_ENABLE_SSL
HX::net::SslContext::get().init<SslContext::SslType::Server>({
SslVerifyOption::None,
"certs/server.crt",
"certs/server.key"
});
#endif
Sources: examples/Server/02_https_server.cpp:94-100
Summary
The HTTP(S) Server & Endpoints module provides a flexible architecture for building C++ web services. By leveraging C++20 coroutines, it allows developers to write asynchronous code that appears synchronous, simplifying complex flows like file I/O and WebSocket handshakes. The inclusion of AOP and advanced routing makes it suitable for both simple APIs and complex resource servers.
Sources: include/HXLibs/net/protocol/http/Response.hpp:29, examples/Server/01_http_server.cpp:129