Em nosso post anterior Exemplo minimal de servidor HTTP Boost::Beast usando boost::json mostramos um exemplo minimal de um servidor web baseado em Boost::Beast em C++ moderno.
Neste post, estenderemos este exemplo para incluir roteamento de requisições usando Boost::URL.
HOWTO de roteamento de requisições
Roteamento das requisições é simples:
httpserver.cpp
url_view parsed_url(req.target());
auto params = parsed_url.params();
// NOTA: O caminho é /api/login para o exemplo acima
auto path = parsed_url.path();
if(path == "/hello") {
// TODO: Tratar /hello
} else if(path == "/world") {
// TODO: Tratar /world
} else {
res.result(http::status::not_found);
res.set(http::field::content_type, "text/plain");
res.body() = "Not Found";
res.prepare_payload();
}Exemplo 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; // de <boost/beast.hpp>
namespace http = beast::http; // de <boost/beast/http.hpp>
namespace net = boost::asio; // de <boost/asio.hpp>
namespace json = boost::json; // de <boost/json.hpp>
using tcp = boost::asio::ip::tcp; // de <boost/asio/ip/tcp.hpp>
// Função para tratar uma requisição HTTP e gerar uma resposta JSON
void handle_request(const http::request<http::string_body>& req, http::response<http::string_body>& res) {
// Para este exemplo, apenas requisições GET
if (req.method() == http::verb::get) {
// NOTA: Para http://127.0.0.1:8080/api/login?username=myusername&password=mypassword
// req.target() será /api/login?username=myusername&password=mypassword
url_view parsed_url(req.target());
auto params = parsed_url.params();
// NOTA: O caminho é /api/login para o exemplo acima
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();
}
}
// Sessão para tratar a comunicação com um único cliente
void session(tcp::socket socket) {
try {
beast::flat_buffer buffer;
// Ler uma requisição HTTP
http::request<http::string_body> req;
http::read(socket, buffer, req);
// Preparar a resposta
http::response<http::string_body> res;
handle_request(req, res);
// Escrever a resposta
http::write(socket, res);
} catch (const std::exception& e) {
std::cerr << "Error in session: " << e.what() << '\n';
}
}
// Função principal para configurar o servidor
int main() {
try {
const auto address = net::ip::make_address("127.0.0.1");
const unsigned short port = 8080;
net::io_context ioc;
// Criar e vincular o aceitador (acceptor)
tcp::acceptor acceptor{ioc, {address, port}};
std::cout << "HTTP server is running on http://127.0.0.1:8080\n";
while (true) {
// Aceitar uma nova conexão
tcp::socket socket{ioc};
acceptor.accept(socket);
// Tratar a sessão em uma nova thread
std::thread{&session, std::move(socket)}.detach();
}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
return 1;
}
}Como compilar
build-httpserver.sh
g++ -std=c++17 -O2 httpserver.cpp -o httpserver -lboost_system -lboost_url -lboost_thread -lboost_json -lpthreadComo testar
No seu terminal, execute:
run-httpserver.sh
./httpserverAbra seu navegador e navegue até http://127.0.0.1:8080/hello e http://127.0.0.1:8080/world para ver as respostas JSON.
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow