Search code examples
clinuxhttpurl-parsing

How to read URLs containing question marks in C using microhttpd.h


I am trying to parse the URL in C using microhttpd library.

daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END);

When I run the function MHD_start_daemon a call back function answer_to_connection is called.

static int answer_to_connection(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls)
{
    printf("URL:%s\n", url);
}

One of the parameters of answer_to_connection is const char *url. The url variable contains the string after https://localhost:port example: for http://128.19.24.123:8888/cars/ferrari the url value will be /cars/ferrari

But in case of http://128.19.24.123:8888/cars?value=ferrari the url is printing only cars.

I want to print cars?value=ferrari. How can I do that?

There is a tutorial on microhttpd library at https://www.gnu.org/software/libmicrohttpd/tutorial.html

But I can't find any solution to this problem there.


Solution

  • CAVEAT EMPTOR: I have not used this library, this answer is based on a quick perusal of the API.

    It looks like you can't access the whole original URL, because microhttpd parses it for you. Instead you access the individual query string values using MHD_lookup_connection_value, like this:

    value = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "value");
    

    That would return a pointer to the value of the query string argument, or null if not found.

    You can also use MHD_get_connection_values to iterate over the query string components. In that case you would call it like this:

    num = MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND, iterator, cls);
    

    iterator would be a callback function to receive the GET query arguments, one by one.

    See also: the Handling requests section in the manual.