Get values from RESTinio key-value containers

When working with key-value containers (restinio::query_string_params_t or restinio::router::route_params_t) there is a common situation when one would like to obtain the value of some parameter (referenced by key) or a default value in case the parameter with a given key is absent. Another common situation is to obtain optional<T> with the real value casted to a given type or an empty instance in case parameter with a given key is absent.

Since of v.0.4.4 RESTinio allows to handle the first situation easely. There is a function restinio::value_or(). And Since of v.0.4.5.1 RESTinio allows to handle the second situation also. There is a function restinio::opt_value().

value_or()

template < typename Value_Type, typename Parameter_Container >
Value_Type value_or(
  const Parameter_Container & params,
  string_view_t key,
  Value_Type default_value );

This function gets the value of a parameter specified by key if the parameter exists. If the parameter exists in params it is obtained as string_view_t object and casted to a necessary type and then returns. If params has no such parameter then the default_value is returned.

A sample code using this function:

 router->http_get(
     R"-(/rand/nums)-",
     [ & ]( restinio::request_handle_t req, auto ){

         const auto qp = restinio::parse_query( req->header().query() );
         const std::size_t count = restinio::value_or( qp, "count", 100u );

         if( count < count_threshold )
         {
             // ...
         }
         else
         {
             // ...
         }
     } );

opt_value()

template < typename Value_Type, typename Parameter_Container >
Value_Type value_or(
  const Parameter_Container & params,
  string_view_t key );

This function gets the value of a parameter specified by key if the parameter exists. If the parameter exists in params it is obtained as string_view_t object and casted to a necessary type and then wrapped into optional type and returned. If params has no such parameter then empty optional instance returned.

A sample code using this function:

 router->http_get(
     R"-(/rand/nums)-",
     [ & ]( restinio::request_handle_t req, auto ){
         const auto qp = restinio::parse_query( req->header().query() );
         handle_data( restinio::opt_value<std::size_t>( qp, "count" ) )
     } );