Created
December 26, 2012 07:01
-
-
Save anonymous/4378563 to your computer and use it in GitHub Desktop.
http-parser example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include "http_parser.h" | |
#define MAX_DATA 1024 | |
int on_message_begin(http_parser *parser) | |
{ | |
printf("on_message_begin\n"); | |
return 0; | |
} | |
int on_url(http_parser *parser, const char *data, size_t length) | |
{ | |
printf("on_url\n"); | |
return 0; | |
} | |
int on_status_complete(http_parser *parser) | |
{ | |
printf("on_status_complete\n"); | |
return 0; | |
} | |
int on_header_field(http_parser *parser, const char *data, size_t length) | |
{ | |
printf("on_header_field\n"); | |
return 0; | |
} | |
int on_header_value(http_parser *parser, const char *data, size_t length) | |
{ | |
printf("on_header_value\n"); | |
return 0; | |
} | |
int on_headers_complete(http_parser *parser) | |
{ | |
printf("on_headers_complete\n"); | |
return 0; | |
} | |
int on_body(http_parser *parser, const char *data, size_t length) | |
{ | |
printf("on_body\n"); | |
return 0; | |
} | |
int on_message_complete(http_parser *parser) | |
{ | |
printf("on_message_complete\n"); | |
return 0; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc != 2) { | |
printf("Usage: %s file\n", argv[0]); | |
return 1; | |
} | |
http_parser_settings settings; | |
settings.on_message_begin = on_message_begin; | |
settings.on_url = on_url; | |
settings.on_status_complete = on_status_complete; | |
settings.on_header_field = on_header_field; | |
settings.on_header_value = on_header_value; | |
settings.on_headers_complete = on_headers_complete; | |
settings.on_body = on_body; | |
settings.on_message_complete = on_message_complete; | |
http_parser *parser = malloc(sizeof(http_parser)); | |
http_parser_init(parser, HTTP_REQUEST); | |
int file; | |
if ((file = open(argv[1], O_RDONLY)) == -1) { | |
printf("Cannot open file\n"); | |
return 1; | |
} | |
size_t n_read; | |
char data[MAX_DATA]; | |
if ((n_read = read(file, &data, MAX_DATA)) == -1) { | |
printf("read error\n"); | |
return 1; | |
} | |
size_t nparsed; | |
nparsed = http_parser_execute(parser, &settings, data, n_read); | |
if (nparsed != n_read) { | |
printf("parse error\n"); | |
return 1; | |
} | |
close(file); | |
free(parser); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment