1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
|
# HTTP Server
The Glaze HTTP server provides a high-performance, async HTTP server implementation using ASIO.
> **Prerequisites:** This feature requires ASIO. See the [ASIO Setup Guide](asio-setup.md) for installation instructions.
## Basic Usage
### Creating a Server
```cpp
#include "glaze/net/http_server.hpp"
#include <iostream>
glz::http_server server;
// Configure routes
server.get("/hello", [](const glz::request& /*req*/, glz::response& res) {
res.body("Hello, World!");
});
// Note: start() is non-blocking; block main until shutdown
server.bind("127.0.0.1", 8080)
.with_signals(); // handle Ctrl+C (SIGINT)
std::cout << "Server running on http://127.0.0.1:8080\n";
std::cout << "Press Ctrl+C to stop\n";
server.start();
server.wait_for_signal();
```
### HTTPS Server
```cpp
#include "glaze/net/http_server.hpp"
// Create HTTPS server (template parameter enables TLS)
glz::https_server server; // or glz::http_server<true>
// Load SSL certificates
server.load_certificate("cert.pem", "key.pem");
server.set_ssl_verify_mode(0); // No client verification
server.get("/secure", [](const glz::request& req, glz::response& res) {
res.json({{"secure", true}, {"message", "This is HTTPS!"}});
});
server.bind(8443);
server.start();
```
## Server Configuration
### Binding and Ports
```cpp
// Bind to specific address and port
server.bind("127.0.0.1", 8080);
// Bind to all interfaces
server.bind("0.0.0.0", 8080);
// Bind to port only (defaults to all interfaces)
server.bind(8080);
// IPv6 support
server.bind("::1", 8080); // localhost IPv6
server.bind("::", 8080); // all IPv6 interfaces
```
### Thread Pool Configuration
```cpp
// Start with default thread count (hardware concurrency, minimum 1)
server.start(); // Uses std::thread::hardware_concurrency(), minimum 1 thread
// Start with specific number of threads
server.start(4); // 4 worker threads
// Start without creating worker threads (for external io_context management)
server.start(0); // No worker threads - caller manages io_context::run()
```
### Error Handling
You can provide a custom error handler either in the constructor or using `on_error()`:
```cpp
// Option 1: Provide error handler in constructor
auto error_handler = [](std::error_code ec, std::source_location loc) {
std::fprintf(stderr, "Server error at %s:%d: %s\n",
loc.file_name(), loc.line(), ec.message().c_str());
};
glz::http_server server(nullptr, error_handler);
// Option 2: Set error handler after construction
server.on_error([](std::error_code ec, std::source_location loc) {
std::fprintf(stderr, "Server error at %s:%d: %s\n",
loc.file_name(), loc.line(), ec.message().c_str());
});
```
### Using an External io_context
You can provide your own `asio::io_context` to the server, allowing you to share the event loop with other ASIO-based components or manage the lifecycle externally.
```cpp
#include "glaze/net/http_server.hpp"
#include <asio/io_context.hpp>
#include <memory>
#include <thread>
// Create a shared io_context
auto io_ctx = std::make_shared<asio::io_context>();
// Pass it to the server constructor
glz::http_server server(io_ctx);
// Configure routes
server.get("/hello", [](const glz::request&, glz::response& res) {
res.body("Hello, World!");
});
// Bind the server
server.bind(8080);
// Start server without creating worker threads (pass 0)
server.start(0);
// Run io_context in your own thread(s)
std::thread io_thread([io_ctx]() {
io_ctx->run();
});
// ... later, when shutting down ...
server.stop();
io_ctx->stop();
io_thread.join();
```
This is useful when:
- You want to share an io_context between multiple ASIO components (e.g., multiple servers or clients)
- You need fine-grained control over thread management
- You're integrating the server into an existing ASIO-based application
**Important:** When using an external io_context, pass `0` to `start()` to prevent the server from creating its own worker threads. You are then responsible for calling `io_context::run()` in your own threads.
## Route Registration
### Basic Routes
```cpp
// GET route
server.get("/users", [](const glz::request& req, glz::response& res) {
res.json(get_all_users());
});
// POST route
server.post("/users", [](const glz::request& req, glz::response& res) {
User user;
if (auto ec = glz::read_json(user, req.body)) {
res.status(400).body("Invalid JSON");
return;
}
create_user(user);
res.status(201).json(user);
});
// Multiple HTTP methods
server.route(glz::http_method::PUT, "/users/:id", handler);
server.route(glz::http_method::DELETE, "/users/:id", handler);
```
### Route Parameters
```cpp
// Path parameters with :param syntax
server.get("/users/:id", [](const glz::request& req, glz::response& res) {
int user_id = std::stoi(req.params.at("id"));
res.json(get_user_by_id(user_id));
});
// Multiple parameters
server.get("/users/:user_id/posts/:post_id",
[](const glz::request& req, glz::response& res) {
int user_id = std::stoi(req.params.at("user_id"));
int post_id = std::stoi(req.params.at("post_id"));
res.json(get_user_post(user_id, post_id));
});
// Wildcard parameters with *param syntax
server.get("/files/*path", [](const glz::request& req, glz::response& res) {
std::string file_path = req.params.at("path");
serve_static_file(file_path, res);
});
```
### Parameter Constraints
```cpp
// Numeric ID constraint
glz::param_constraint id_constraint{
.description = "User ID must be numeric",
.validation = [](std::string_view value) {
if (value.empty()) return false;
for (char c : value) {
if (!std::isdigit(c)) return false;
}
return true;
}
};
server.get("/users/:id", handler, {{"id", id_constraint}});
// Email constraint
glz::param_constraint email_constraint{
.description = "Valid email address required",
.validation = [](std::string_view value) {
std::regex email_regex(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
return std::regex_match(std::string(value), email_regex);
}
};
```
## Response Handling
### Response Builder
```cpp
server.get("/api/data", [](const glz::request& req, glz::response& res) {
// Set status code
res.status(200);
// Set headers
res.header("X-Custom-Header", "value");
res.content_type("application/json");
// Set body
res.body("{\"message\": \"Hello\"}");
// Method chaining
res.status(201)
.header("Location", "/api/data/123")
.json({{"id", 123}, {"created", true}});
});
```
### JSON Responses
```cpp
// Automatic JSON serialization
struct User {
int id;
std::string name;
std::string email;
};
server.get("/users/:id", [](const glz::request& req, glz::response& res) {
User user = get_user(std::stoi(req.params.at("id")));
res.json(user); // Automatically serializes to JSON
});
// Using glz::opts for custom serialization
server.get("/users/:id/detailed", [](const glz::request& req, glz::response& res) {
User user = get_user(std::stoi(req.params.at("id")));
res.body<glz::opts{.prettify = true}>(user); // Pretty-printed JSON
});
```
### Error Responses
```cpp
server.get("/users/:id", [](const glz::request& req, glz::response& res) {
try {
int id = std::stoi(req.params.at("id"));
User user = get_user(id);
if (user.id == 0) {
res.status(404).json({{"error", "User not found"}});
return;
}
res.json(user);
} catch (const std::exception& e) {
res.status(400).json({{"error", "Invalid user ID"}});
}
});
```
## Middleware
### Adding Middleware
```cpp
// Logging middleware
server.use([](const glz::request& req, glz::response& res) {
std::cout << glz::to_string(req.method) << " " << req.target << std::endl;
});
// Authentication middleware
server.use([](const glz::request& req, glz::response& res) {
// Note: Header names are case-insensitive (RFC 7230)
if (req.headers.find("authorization") == req.headers.end()) {
res.status(401).json({{"error", "Authorization required"}});
return;
}
// Validate token...
});
// CORS middleware (built-in)
server.enable_cors();
```
### Custom Middleware
```cpp
// Rate limiting middleware
auto rate_limiter = [](const glz::request& req, glz::response& res) {
static std::unordered_map<std::string, int> request_counts;
auto& count = request_counts[req.remote_ip];
if (++count > 100) { // 100 requests per IP
res.status(429).json({{"error", "Rate limit exceeded"}});
return;
}
};
server.use(rate_limiter);
```
### Wrapping Middleware
Wrapping middleware executes around handlers, allowing code execution both before and after the handler completes.
```cpp
// Timing and metrics middleware
server.wrap([](const glz::request& req, glz::response& res, const auto& next) {
auto start = std::chrono::steady_clock::now();
next(); // Execute next middleware or handler
auto duration = std::chrono::steady_clock::now() - start;
std::cout << req.target << " completed in "
<< std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()
<< "ms\n";
});
```
#### ⚠️ Safety Requirements
**The `next()` handler MUST be called synchronously.** The `next` parameter is intentionally non-copyable and non-movable to prevent accidental storage and asynchronous invocation, which would cause dangling references.
✅ **Correct - Synchronous execution:**
```cpp
server.wrap([](const glz::request& req, glz::response& res, const auto& next) {
// Do work before
next(); // Call synchronously
// Do work after
});
```
❌ **Incorrect - Will not compile:**
```cpp
server.wrap([](const glz::request& req, glz::response& res, const auto& next) {
// ✗ COMPILE ERROR: next is non-copyable
std::thread([next]() {
next();
}).detach();
});
```
For asynchronous operations, complete them **before** or **after** calling `next()`:
```cpp
server.wrap([](const glz::request& req, glz::response& res, const auto& next) {
// Async work BEFORE handler
auto data = fetch_data_async().get();
next(); // Synchronous handler execution
// Fire-and-forget async work AFTER (using copied values only)
std::async([status = res.status_code]() {
log_to_remote(status);
});
});
```
#### Use Cases
**Request/Response Timing:**
```cpp
struct Metrics {
std::atomic<uint64_t> total_requests{0};
std::atomic<uint64_t> total_responses{0};
std::atomic<double> response_time_sum{0.0};
};
Metrics metrics;
server.wrap([&metrics](const glz::request&, glz::response& res, const auto& next) {
metrics.total_requests++;
auto start = std::chrono::steady_clock::now();
next();
auto duration = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
metrics.response_time_sum += duration;
metrics.total_responses++;
});
```
**Error Handling:**
```cpp
server.wrap([](const glz::request&, glz::response& res, const auto& next) {
try {
next();
} catch (const std::exception& e) {
res.status(500).json({{"error", "Internal server error"}});
log_error(e.what());
}
});
```
**Response Transformation:**
```cpp
server.wrap([](const glz::request&, glz::response& res, const auto& next) {
next();
// Add security headers after handler completes
res.header("X-Content-Type-Options", "nosniff");
res.header("X-Frame-Options", "DENY");
res.header("X-XSS-Protection", "1; mode=block");
});
```
**Logging with Full Context:**
```cpp
server.wrap([](const glz::request& req, glz::response& res, const auto& next) {
auto start = std::chrono::steady_clock::now();
next();
auto duration = std::chrono::steady_clock::now() - start;
log_request(req.method, req.target, res.status_code, duration);
});
```
#### Execution Order
Multiple wrapping middleware execute in the order they are registered:
```cpp
server.wrap([](const glz::request&, glz::response&, const auto& next) {
std::cout << "Middleware 1 before\n";
next();
std::cout << "Middleware 1 after\n";
});
server.wrap([](const glz::request&, glz::response&, const auto& next) {
std::cout << "Middleware 2 before\n";
next();
std::cout << "Middleware 2 after\n";
});
// Output order:
// Middleware 1 before
// Middleware 2 before
// Handler executes
// Middleware 2 after
// Middleware 1 after
```
## Mounting Sub-routers
```cpp
// Create sub-router for API v1
glz::http_router api_v1;
api_v1.get("/users", get_users_handler);
api_v1.post("/users", create_user_handler);
// Create sub-router for API v2
glz::http_router api_v2;
api_v2.get("/users", get_users_v2_handler);
// Mount sub-routers
server.mount("/api/v1", api_v1);
server.mount("/api/v2", api_v2);
// Now routes are available at:
// GET /api/v1/users
// POST /api/v1/users
// GET /api/v2/users
```
## Static File Serving
```cpp
// Serve static files from directory
server.get("/static/*path", [](const glz::request& req, glz::response& res) {
std::string file_path = "public/" + req.params.at("path");
std::ifstream file(file_path);
if (!file.is_open()) {
res.status(404).body("File not found");
return;
}
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// Set appropriate content type
if (file_path.ends_with(".html")) {
res.content_type("text/html");
} else if (file_path.ends_with(".css")) {
res.content_type("text/css");
} else if (file_path.ends_with(".js")) {
res.content_type("application/javascript");
}
res.body(content);
});
```
## Server Lifecycle
### Starting and Stopping
```cpp
// Simple server with signal handling
int main() {
glz::http_server server;
// Configure routes
server.get("/api/hello", [](const glz::request&, glz::response& res) {
res.json({{"message", "Hello, World!"}});
});
// Bind and enable signal handling
server.bind(8080)
.with_signals();
// Start server
server.start();
// Wait for shutdown signal
server.wait_for_signal();
return 0;
}
```
For integration into larger applications:
```cpp
class APIServer {
glz::http_server server_;
public:
bool start(uint16_t port) {
try {
configure_routes();
server_.bind(port)
.with_signals(); // Enable signal handling
// Start server (non-blocking)
server_.start();
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to start server: " << e.what() << std::endl;
return false;
}
}
void wait_for_shutdown() {
server_.wait_for_signal();
}
void stop() {
server_.stop();
}
private:
void configure_routes() {
server_.get("/health", [](const glz::request&, glz::response& res) {
res.json({{"status", "healthy"}});
});
}
};
```
### Graceful Shutdown
```cpp
// Built-in signal handling (recommended approach)
int main() {
glz::http_server server;
// Configure routes
setup_routes(server);
// Enable signal handling for graceful shutdown (handles SIGINT/SIGTERM)
server.bind(8080)
.with_signals();
std::cout << "Server running on http://localhost:8080" << std::endl;
std::cout << "Press Ctrl+C to gracefully shut down the server" << std::endl;
// Start server
server.start();
// Wait for shutdown signal (blocks until server stops)
server.wait_for_signal();
std::cout << "Server shut down successfully" << std::endl;
return 0;
}
```
For more control, you can still implement custom signal handling:
```cpp
#include <csignal>
std::atomic<bool> running{true};
glz::http_server server;
void signal_handler(int signal) {
std::cout << "Received signal " << signal << ", shutting down..." << std::endl;
running = false;
server.stop();
}
int main() {
// Register signal handlers
std::signal(SIGINT, signal_handler);
std::signal(SIGTERM, signal_handler);
// Configure server
setup_routes(server);
server.bind(8080);
// Start server
std::future<void> server_future = std::async(std::launch::async, [&]() {
server.start();
});
// Wait for shutdown signal
while (running) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
server_future.wait();
return 0;
}
```
## Production Configuration
### Performance Tuning
```cpp
// Optimize for production
server.bind("0.0.0.0", 8080);
// Use multiple threads (typically CPU cores)
int num_threads = std::thread::hardware_concurrency();
server.start(num_threads);
// Configure error handling for production
server.on_error([](std::error_code ec, std::source_location loc) {
// Log to file/service instead of stderr
if (should_log_error(ec)) {
log_error(ec, loc);
}
});
```
### Connection Management (Keep-Alive)
The HTTP server supports HTTP/1.1 persistent connections (keep-alive) for improved performance. By default, keep-alive is enabled with a 60-second idle timeout.
#### Configuration Options
```cpp
// Configure all connection settings at once
server.connection_settings({
.keep_alive = true, // Enable persistent connections (default: true)
.keep_alive_timeout = 30, // Idle timeout in seconds (default: 60)
.max_requests_per_connection = 100 // Max requests per connection (default: 0 = unlimited)
});
// Or configure individual settings
server.keep_alive(true) // Enable/disable keep-alive
.keep_alive_timeout(30) // Set idle timeout
.max_requests_per_connection(100); // Set max requests limit
```
#### Disabling Keep-Alive
If you experience connection issues with certain clients, you can disable keep-alive:
```cpp
// Disable keep-alive entirely
server.keep_alive(false);
// Or use connection_settings
server.connection_settings({
.keep_alive = false
});
```
When keep-alive is disabled, the server sends `Connection: close` with every response and closes the connection after each request/response cycle.
#### Behavior Details
- **HTTP/1.1 clients**: Keep-alive is enabled by default (per HTTP/1.1 spec)
- **HTTP/1.0 clients**: Keep-alive is disabled unless client sends `Connection: keep-alive`
- **Client requests close**: If client sends `Connection: close`, server respects it
- **Idle timeout**: Connections are closed after the configured timeout of inactivity
- **Max requests**: Connections are closed after reaching the request limit (if configured)
The server always sends the appropriate `Connection` header (`keep-alive` or `close`) and a `Keep-Alive` header with timeout information when keep-alive is active.
### Health Checks
```cpp
// Health check endpoint
server.get("/health", [](const glz::request&, glz::response& res) {
// Check database connection, external services, etc.
bool healthy = check_database() && check_external_apis();
if (healthy) {
res.json({
{"status", "healthy"},
{"timestamp", get_timestamp()},
{"version", VERSION}
});
} else {
res.status(503).json({
{"status", "unhealthy"},
{"timestamp", get_timestamp()}
});
}
});
// Readiness check for Kubernetes
server.get("/ready", [](const glz::request&, glz::response& res) {
if (is_ready_to_serve()) {
res.json({{"status", "ready"}});
} else {
res.status(503).json({{"status", "not ready"}});
}
});
```
|