Query string parameters

When handling incoming requests sometimes it is necessary to deal with query string parameter. For example, the following URL: http://example.com/location?country=canada&minrating=4&mindate=20180101 has 3 query parameters. Though one can obtain a raw query string from request header (see Request header) it is more convenient to use restinio::parse_query() function to get a key-value interface object to work with parameters:

query_string_params_t parse_query( string_view_t query_string );

Class query_string_params_t has the following interface:

class query_string_params_t
{
    // ...

    string_view_t operator [] ( string_view_t key ) const;

    optional_t< string_view_t > get_param( string_view_t key ) const;

    bool has( string_view_t key ) const;
    auto size() const;

    auto begin() const;
    auto end() const;

    // ...
};

Parameters values are represented with string view. And of course one can cast parameters values with restinio::cast_to<T>().

A sample code for working with query string parameters:

restinio::request_handling_status_t handler( restinio::request_handle_t req )
{
    if( restinio::http_method_get() == req->header().method() )
    {
        std::ostringstream sout;
        sout << "GET request to '" << req->header().request_target() << "'\n";

        // Query params.
        const auto qp = restinio::parse_query( req->header().query() );

        if( 0 == qp.size() )
        {
            sout << "No query parameters.";
        }
        else
        {
            sout << "Query params ("<< qp.size() << "):\n";

            for( const auto p : qp )
            {
                sout << "'"<< p.first << "' => "<<  p.second << "'\n";
            }
        }

        if( qp.has( "debug" ) && qp[ "debug" ] == "true" )
        {
            std::cout << sout.str() << std::endl;
        }

        req->create_response()
            .append_header( restinio::http_field::server, "RESTinio query string params server" )
            .append_header_date_field()
            .append_header( restinio::http_field::content_type, "text/plain; charset=utf-8" )
            .set_body( sout.str() )
            .done();

        return restinio::request_accepted();
    }

    return restinio::request_rejected();
}

But it is more convenient to use special functions to get values from restinio key-value objects: value_or() and opt_value(), refer to Get values from RESTinio key-value containers section for details.

See also a full sample.