You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正确访问boost::beast::http::request对象的方法

正确访问boost::beast::http::request对象的方法

看起来你已经用std::shared_ptr来托管request和buffer对象了,这步做得很稳妥——毕竟异步回调的执行时机不确定,用智能指针能完美避免对象提前销毁导致的悬空指针问题。

在你的异步回调函数里,要正确访问request对象其实很简单,直接利用shared_ptr的箭头操作符或者解引用就行,给你举几个常用的访问场景:

  • 访问请求的基础属性:用request->来调用成员函数,比如获取请求方法、目标URI、头部信息这些:

    // 获取请求方法(比如GET、POST)
    auto method = request->method();
    // 获取请求的目标路径
    auto target = request->target();
    // 查找指定的请求头
    auto auth_header = request->find(boost::beast::http::field::authorization);
    
  • 访问请求体:如果是string_body类型的request,直接通过request->body()就能拿到请求体的字符串内容:

    std::string& body_content = request->body();
    // 比如打印请求体
    std::cout << "Request Body: " << body_content << std::endl;
    
  • 传递整个request对象:如果需要把request传给其他函数处理,直接解引用shared_ptr得到对象引用即可:

    // 假设handle_http_request函数接受request的引用
    handle_http_request(*request);
    

给你把这些用法整合到你的回调代码里,看起来更直观:

[socket, buffer, request](const boost::system::error_code& ec, std::size_t bytes_transferred) {
    if (!ec) {
        // 处理请求的逻辑
        std::cout << "Received request method: " << request->method_string() << std::endl;
        std::cout << "Request path: " << request->target() << std::endl;
        
        // 读取请求体
        if (!request->body().empty()) {
            std::cout << "Request body length: " << request->body().size() << std::endl;
        }
        
        // 传给其他处理函数
        process_incoming_request(*request);
    } else {
        // 处理错误
        std::cerr << "Read error: " << ec.message() << std::endl;
    }
}

最后再提个小提醒:因为你用shared_ptr捕获了request和buffer,只要回调还在执行,这两个对象就会保持存活状态,完全不用手动管理它们的生命周期,智能指针会帮你搞定一切~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 12:53:15