2009-01-19

Accessing GET arguments with libmicrohttpd

The tutorial for libmicrohttpd talks about handling POST arguments, but what if your FORM uses GET? The solution's easy, but I had to work to find it, so this might save someone some trouble in future...

The tutorial contains this example to dump the HTTP headers:

  MHD_get_connection_values(connection, MHD_HEADER_KIND, print_out_key, NULL);

What it doesn't mention is the alternatives to MHD_HEADER_KIND. You don't need to parse the "Referer:" header yourself, as I was about to fall back on; you just need to look at the MHD_GET_ARGUMENT_KIND values. (Or, if it's cookies you're wanting, MHD_COOKIE_KIND.)

Even better, given that you probably know the name of the cookie, GET argument, or header you're looking for in any real code, there's MHD_lookup_connection_value. Here's how you'd get the value of a GET argument called "q", for example:

  const char* q = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "q");

Don't go putting that straight into a std::string, because libmicrohttpd returns NULL for missing values.

Why am I using libmicrohttpd? Well, that's a story for another day. I'm writing this post because I don't start dealing with the little jobs as soon as they come to me, I'm going to suffer stack overflow.