Search code examples
cunixlibevent

How to read evbuffer and put it into a string (char*) in libevent


I am using libevent and its http API to write a simple HTTP server capable of writing C servlets. This servlet is working ok with GET but now I am sending some data with POST and I would like to read the incoming event buffer evb. I would like to print/inspect the data present in evb but I cannot. Do you know how I can put the data in evb (evbuffer) in char* variable? I saw only methods to manipulate buffers but not reading it. I tried:

evb->

This is the code:

    #include <stdio.h>
    #include "servlet.h"

    void servlet(struct evhttp_request *req, struct evbuffer *evb) {
        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>",
            "C servlet engine", "C servlet", ctime(&now));
        evhttp_add_header(evhttp_request_get_output_headers(req),
            "Content-Type", "text/html");
        evhttp_send_reply(req, 200, "OK", evb);
    }

I am trying this 

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;
    evbuffer_copyout(in_evb, data, len);

but I get Bus error: 10 (I am on a mac)


Solution

  • Sounds like you want to use

    ev_ssize_t evbuffer_copyout(struct evbuffer *buf, void *data, size_t datalen)
    

    It copies the buffer contents (at most datalen bytes) to the memory area data. It's documented in the libevent book