是否有可能在中介区拥有动态路线?

时间:2018-06-12 20:21:08

标签: c++ http pion-net

我想在VS2017 c ++项目中使用 pion 5.0.6 作为小型网络服务器。对于静态路由,我可以使用

add_resource("/my/static/route", <handler>)

我也需要动态路线 - 比如"/data/:id/info 我该怎么做?

1 个答案:

答案 0 :(得分:0)

对于那些可能需要它的人:我找到了添加动态路由 pion 网络服务器的解决方案。它需要我在hxoht on github找到的智能路由器代码,并按照

的方式工作
  • 所有路线 - 静态和动态 - 均使用httpd->add_resource(<url>, <handler);
  • 设置
  • 必须使用httpd->set_not_found_handler(<handler>);设置404处理程序,并负责将动态路由分派给上面添加的处理程序。
  • 您的网络服务器类必须从pion::http::server派生才能按名称httpd->find_request_handler(<url>, <handler>);
  • 查找处理程序 在您的404处理程序中,
  • 使用Match::test(<dynamic-route>)方法检测动态路由 - 如下面的代码片段所示:

    void handle_404(http::request_ptr& req, tcp::connection_ptr& con)
    {
        Route target;
        Match dynamic = target.set(req->get_resource());
        for (auto& route : dynamic_routes) // Our list of dynamic routes
        {
            if (dynamic.test(route)) // Does the url match the dynamic route pattern?
            {
                request_handler_t h;
                if (find_request_handler(route, h))
                {
                    auto name = get_param_name(route); // e.g. /a/:b -> "b"
                    value = dynamic.get(name); // Save value in string or map<name, value>
                    h(req, con); // Call original handler with value set properly
                    return;
                }
            }
        }
        // If no match then return a 404.
        http::response_writer_ptr w(http::response_writer::create(con, *req,
        boost::bind(&tcp::connection::finish, con)));
        http::response& res = w->get_response();
        res.set_status_code(http::types::RESPONSE_CODE_NOT_FOUND);
        res.set_status_message(http::types::RESPONSE_MESSAGE_NOT_FOUND);
        w->send();
    }
    

为了以多线程方式使用 pion 网络服务器,我会将解析后的值存储在请求中 object,它将派生自pion::http::request

这适用于 Windows Linux :)

相关问题