Search code examples
curllibevent

libevent evhttp how do I get the body length or indeed any body data?


Using the simple example below I'm trying to extract the data from the body of a post generated like so:

curl -v -X POST http://localhost:1067/POST <

The output I get is as described below:

$ ./evh len=0 req=

Please HELP!

void process_request(struct evhttp_request *req, void *arg){ 
    struct evbuffer *buf;
    size_t len;
    char *data=malloc(1000);

    if (buf == NULL) return;

    buf=evhttp_request_get_input_buffer(req);

    len=evbuffer_copyout(buf, data, 1000);

    printf("len=%d req=%.*s\n", (int)len, (int)len, data);

    evbuffer_add_printf(buf, "Requested: %s\n", evhttp_request_uri(req));
    evhttp_send_reply(req, HTTP_OK, "OK", buf);
}

Solution

  • Hope this will help :

    void process_request(struct evhttp_request* req, void* arg){ 
        struct evbuffer* buf = null;
        size_t len = 0;
        char* data = null;
    
        if (req == NULL) return; // req is null after a timeout
    
        // get the event buffer containing POST body
        buf = evhttp_request_get_input_buffer(req);
    
        // get the length of POST body
        len = evbuffer_get_length(buf);
    
        // create a char array to extract POST body
        data = malloc(len + 1);
        data[len] = 0;
    
        // copy POST body into your char array
        evbuffer_copyout(buf, data, len);
    
        [...]
    
        // release memory
        free(data);
    }