Skip to content
This repository has been archived by the owner on Nov 6, 2022. It is now read-only.

Cannot parse message without specifying Transfer-Encoding: chunked #434

Closed
dxdx347 opened this issue Jun 15, 2018 · 4 comments
Closed

Cannot parse message without specifying Transfer-Encoding: chunked #434

dxdx347 opened this issue Jun 15, 2018 · 4 comments

Comments

@dxdx347
Copy link

dxdx347 commented Jun 15, 2018

Hello! I am trying to parse the following message:

HTTP/1.1 200 OK
Server: Cowboy
Date: Fri, 15 Jun 2018 10:30:14 GMT
Content-Type: application/json
Content-Length: 18
Via: 1.1 vegur
Expires: Fri, 15 Jun 2018 12:30:14 GMT
Connection: keep-alive

{"hello": "world"}

It returns content_length = 0. It only works if I add "Transfer-Encoding: chunked". This is my code:

struct http_parser parser;
static http_parser_settings settings = {
  .on_message_begin = on_info,
  .on_headers_complete = on_info,
  .on_message_complete = on_info,
  .on_header_field = on_data,
  .on_header_value = on_data,
  .on_url = on_data,
  .on_status = on_data,
  .on_body = on_data
};

static int on_info(http_parser* p)
{
    return 0;
}

static int on_data(http_parser* p, const char *at, size_t length)
{
    return 0;
}

http_parser_init(&parser, HTTP_BOTH);
size_t parsed;
parsed = http_parser_execute(&parser, &settings, httpMessage, strlen(httpMessage));
char body[500] = "";
strncpy(body, httpMessage+ parsed + 1, parser.content_length + 1);

Is this a bug? Or have I misconfigured something?

@dxdx347
Copy link
Author

dxdx347 commented Jun 15, 2018

I've managed to read the body of the message by saving the number of bytes read in the callback on_headers_complete(). It was my misunderstanding of how the code works.

@ploxiln
Copy link
Contributor

ploxiln commented Jun 15, 2018

http_parser_execute() parsed the entire buffer you passed it, including the body. The body was passed to the on_body callback. After the entire http message was parsed, it reset to initial state to be ready to parse another message.

@indutny
Copy link
Member

indutny commented Jun 15, 2018

Was content_length available in on_message_complete callback? As @ploxiln said, the parser resets its state to initial to prepare for the next message.

@dxdx347
Copy link
Author

dxdx347 commented Jun 15, 2018

I read the number of bytes parsed when headers complete callback is called, not the content length.

static int on_headers_complete(http_parser* p)
{
    dataStartIndex = p->nread;
    return 0;
}

@dxdx347 dxdx347 closed this as completed Jun 15, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants