[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [Libevent-users] parse query string




On Aug 11, 2012, at 6:30 PM, Riccardo Tacconi wrote:

Hi,

I have the following code called from libevent's http-server.c demo:

#include "servlet.h"

void servlet(struct evhttp_request *req, struct evbuffer *evb) {
size_t len = evbuffer_get_length(evhttp_request_get_input_buffer(req));
    struct evbuffer *in_evb = evhttp_request_get_input_buffer(req);
    char *data = malloc(len);
    evbuffer_copyout(in_evb, data, len);
evhttp_parse_query_str(data, evhttp_request_get_input_headers(req));

    time_t now;
    time(&now);

    evbuffer_add_printf(evb, "<html>\n <head>\n"
	    "  <title>%s</title>\n"
	    " </head>\n"
	    " <body>\n"
	    "  <h1>%s</h1>\n"
	    " <p>Current time is: %s</p>"
	    " <p>received data size: %d</p>\n"
	    " <p>received data: %s</p></body></html>",
	    "C servlet title",
	    "C servlet",
	    ctime(&now),
	    (int)len,
	    data);
    evhttp_add_header(evhttp_request_get_output_headers(req),
	    "Content-Type", "text/html");
	evhttp_send_reply(req, 200, "OK", evb);
    free(data);
}

in data I have this string "param1=value1&param2=value2". I would like to use the in-build parser and I added:

evhttp_parse_query_str(data, evhttp_request_get_input_headers(req));

but I am not sure how I can access the parsed key/values and if I am using the right function.

You can url encoded data from the input buffer like this:

// Include the keyvalq_struct header, for creating evkeyvalq struct and accessing keys and values
#include <event2/keyvalq_struct.h>

// Create a evkeyvalq to keep parsed parameters
struct evkeyvalq params;

// Ensure that data is null terminated - evhttp_parse_query_str() expects a null terminated string, but the input buffer may contain non- terminated data.
char *data = malloc(len + 1);
evbuffer_copyout(in_evb, data, len);
data[len] = '\0';

// Parse the query string
evhttp_parse_query_str(data, &params);

// Now you can access the parameters using
const char *value = evhttp_find_header(params, "name");

// If you want to iterate over all values, you can do
struct evkeyval *param;

TAILQ_FOREACH(param, &params, next) {
	// Do something with param->key and param->value
}

// Finally, you have to free the memory allocated for the parameters
evhttp_clear_headers(&params);



***********************************************************************
To unsubscribe, send an e-mail to majordomo@xxxxxxxxxxxxx with
unsubscribe libevent-users    in the body.