How to parse optional query parameters using Boost::URL

In our previous example How to decode query parameters using Boost::URL (minimal example) we showed how to decode query parameters from a URL.

However, that minimal example will crash:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

if the query parameters are missing. This is because *params.find_last("username") will dereference a nullptr if the parameter is missing.

In this example, we show how to check if the parameter is present before accessing it.

#include <iostream>
#include <boost/url.hpp>

using namespace boost::urls;

using std::cout, std::endl;

int main() {
    // Example encoded URL with query parameters
    std::string encoded_url_str = "https://example.com/api/login?password=mypassword";

    // Parse the URL
    url_view parsed_url(encoded_url_str);

    // Access and decode query parameters
    auto params = parsed_url.params();
    if(params.find_last("username") == params.end()) {
        cout << "No username parameter found" << endl;
    } else {
        std::string username = (*params.find_last("username")).value;
        cout << "Decoded username: " << username << endl;
    }

    if(params.find_last("password") == params.end()) {
        cout << "No password parameter found" << endl;
    } else {
        std::string password = (*params.find_last("password")).value;
        cout << "Decoded password: " << password << endl;
    }

    return 0;
}

How to compile

g++ -std=c++17 parse_query.cpp -o parse_query -lboost_url

Run using

./parse_query

Example output

No username parameter found
Decoded password: mypassword