Search code examples
httpc++11boost-asioboost-beast

using different request parser depending on the queried route


I'm Implementing a mini http server using boost beast. the server has two different routes POST /upload/... and the other one is POST /info. The first one is used for uploading some big files and the other one is for hadling json objects. To keep the performance as hight as possible am I trying to parse each route with the suitable parser file_body and string_body/dynamic_body. I was hoping that it is possible to do something like:

http::async_read_header(
            socket_,
            buffer_,
            request_,
            [self](beast::error_code ec, std::size_t)
            {
                if (!ec)
                    self->request_.body().data();
            });

but it seems not possible.

Is there any way to use different request bodies depending on header info?

Many thanks in advance


Solution

  • This should be covered in the docs but here's how to do it: Use the type beast::request_parser<beast::empty_body> to first read the header, and then depending on the contents of the header you move-construct a new parser from the old one with the body type you want. Example:

    // Deferred body type commitment
    request_parser<empty_body> req0;
    ...
    request_parser<string_body> req{std::move(req0)};
    

    You can read the complete documentation on switching body types here: https://www.boost.org/doc/libs/1_69_0/libs/beast/doc/html/beast/ref/boost__beast__http__parser/parser/overload5.html