Ejemplo minimal de servidor HTTP Boost::Beast con enrutamiento de peticiones usando Boost::URL y respuestas JSON

En nuestro post anterior Ejemplo minimal de servidor HTTP Boost::Beast usando boost::json mostramos un ejemplo minimal de un servidor web basado en Boost::Beast en C++ moderno.

En este post, ampliaremos este ejemplo para incluir enrutamiento de peticiones usando Boost::URL.

Cómo hacer enrutamiento de peticiones

Enrutar las peticiones es simple:

httpserver.cpp
url_view parsed_url(req.target());
auto params = parsed_url.params();

// NOTE: Path is /api/login for the example above
auto path = parsed_url.path();

if(path == "/hello") {
    // TODO: Handle /hello
} else if(path == "/world") {
    // TODO: Handle /world
} else {
        res.result(http::status::not_found);
        res.set(http::field::content_type, "text/plain");
        res.body() = "Not Found";
        res.prepare_payload();
}

Ejemplo completo

httpserver.cpp
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio.hpp>
#include <boost/json.hpp>
#include <boost/url.hpp>
#include <iostream>

using namespace boost::urls;
using std::cout, std::endl;

#include <iostream>

namespace beast = boost::beast;     // from <boost/beast.hpp>
namespace http = beast::http;      // from <boost/beast/http.hpp>
namespace net = boost::asio;       // from <boost/asio.hpp>
namespace json = boost::json;      // from <boost/json.hpp>
using tcp = boost::asio::ip::tcp;  // from <boost/asio/ip/tcp.hpp>

// Función para manejar una petición HTTP y generar una respuesta JSON
void handle_request(const http::request<http::string_body>& req, http::response<http::string_body>& res) {
    // Para este ejemplo, solo peticiones GET
    if (req.method() == http::verb::get) {
        // NOTE: For http://127.0.0.1:8080/api/login?username=myusername&password=mypassword
        // req.target() will be /api/login?username=myusername&password=mypassword
        url_view parsed_url(req.target());
        auto params = parsed_url.params();

        // NOTE: Path is /api/login for the example above
        auto path = parsed_url.path();

        if(path == "/hello") {
            json::object json_response;
            json_response["message"] = "Hello, World!";
            json_response["status"] = "success";

            res.result(http::status::ok);
            res.set(http::field::content_type, "application/json");
            res.body() = json::serialize(json_response);
            res.prepare_payload();
        } else if(path == "/world") {
            json::object json_response;
            json_response["message"] = "World, Hello!";
            json_response["status"] = "success";

            res.result(http::status::ok);
            res.set(http::field::content_type, "application/json");
            res.body() = json::serialize(json_response);
            res.prepare_payload();
        } else {
            res.result(http::status::not_found);
            res.set(http::field::content_type, "text/plain");
            res.body() = "Not Found";
            res.prepare_payload();
        }
    } else {
        res.result(http::status::method_not_allowed);
        res.set(http::field::content_type, "text/plain");
        res.body() = "Method Not Allowed";
        res.prepare_payload();
    }
}

// Sesión para manejar la comunicación con un único cliente
void session(tcp::socket socket) {
    try {
        beast::flat_buffer buffer;

        // Leer una petición HTTP
        http::request<http::string_body> req;
        http::read(socket, buffer, req);

        // Preparar la respuesta
        http::response<http::string_body> res;
        handle_request(req, res);

        // Escribir la respuesta
        http::write(socket, res);
    } catch (const std::exception& e) {
        std::cerr << "Error in session: " << e.what() << '\n';
    }
}

// Función principal para configurar el servidor
int main() {
    try {
        const auto address = net::ip::make_address("127.0.0.1");
        const unsigned short port = 8080;

        net::io_context ioc;

        // Crear y enlazar el acceptor
        tcp::acceptor acceptor{ioc, {address, port}};
        std::cout << "HTTP server is running on http://127.0.0.1:8080\n";

        while (true) {
            // Aceptar una nueva conexión
            tcp::socket socket{ioc};
            acceptor.accept(socket);

            // Manejar la sesión en un nuevo hilo
            std::thread{&session, std::move(socket)}.detach();
        }
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << '\n';
        return 1;
    }
}

Cómo compilar

build-httpserver.sh
g++ -std=c++17 -O2 httpserver.cpp -o httpserver -lboost_system -lboost_url -lboost_thread -lboost_json -lpthread

Cómo probar

En tu terminal, ejecuta:

run-httpserver.sh
./httpserver

Abre tu navegador y navega a http://127.0.0.1:8080/hello y http://127.0.0.1:8080/world para ver las respuestas JSON.


Echa un vistazo a artículos similares por categoría: Boost C/C++