Here's an example of an HTTP server using the IXWebSocket library that has two routes: / and /hello. The / route will return a simple "Welcome to the root" message, and the /hello route will return "Hello World."
Example Code
cpp
#include <ixwebsocket/IXHttpServer.h>
#include <iostream>
#include <memory>
int main()
{
// Set up the server on port 8080 and listen on all interfaces
int port = 8080;
std::string host = "[Redacted IPAddress]"; // Bind to all network interfaces
ix::HttpServer server(port, host);
// Define route handling
server.setOnConnectionCallback(
[](ix::HttpRequestPtr request, std::shared_ptr<ix::ConnectionState>) -> ix::HttpResponsePtr {
if (request->uri == "/")
{
// Root route
std::string content = "Welcome to the root";
return std::make_shared<ix::HttpResponse>(
200, "OK", ix::HttpErrorCode::Ok, ix::WebSocketHttpHeaders(), content);
}
else if (request->uri == "/hello")
{
// Hello World route
std::string content = "Hello World";
return std::make_shared<ix::HttpResponse>(
200, "OK", ix::HttpErrorCode::Ok, ix::WebSocketHttpHeaders(), content);
}
else
{
// Handle unknown routes
std::string content = "404 Not Found";
return std::make_shared<ix::HttpResponse>(
404, "Not Found", ix::HttpErrorCode::Ok, ix::WebSocketHttpHeaders(), content);
}
});
// Start the server
auto res = server.listen();
if (!res.first)
{
std::cerr << "Error starting server: " << res.second << std::endl;
return 1;
}
std::cout << "HTTP server is listening on " << host << ":" << port << std::endl;
server.start();
server.wait(); // Block until the server is stopped
return 0;
}
How It Works
Server Initialization: The server is set to listen on port 8080 and bind to all network interfaces ([Redacted IPAddress]).
Route Handling:
For /, it responds with "Welcome to the root".
For /hello, it responds with "Hello World".
For any other route, it responds with "404 Not Found".
Server Start:
The server starts listening for incoming connections.
The server.wait() function blocks the main thread, keeping the server running.
Visit http://localhost:8080/ to see the "Welcome to the root" message.
Visit http://localhost:8080/hello to see the "Hello World" message.
Visit any other path (e.g., http://localhost:8080/unknown) to see the "404 Not Found" message.
Notes
This example uses the setOnConnectionCallback method to define responses for different routes.
You can customize the content type, headers, or response codes as needed. For example, you can return JSON responses by setting the Content-Type header appropriately.