commit 52bda53de10d31e886a996c2722fe396a0700217
parent 80acd513ffaa65c3df2a28c7f5d3e3b3db7df255
Author: finwo <finwo@pm.me>
Date: Sat, 9 Nov 2019 21:03:31 +0100
Added minimal readme
Diffstat:
3 files changed, 40 insertions(+), 4 deletions(-)
diff --git a/README.md b/README.md
@@ -0,0 +1,33 @@
+# http-parser
+
+Small http message parsing library. Keep in mind that this library only handles
+parsing the http request into a method, headers and body.
+
+## Basic usage
+
+```c
+
+static void onRequest(struct http_parser_event *ev) {
+ // The request has been received
+ // Answer the request directly or pass it to a route handler of sorts
+}
+
+// Initialize a request
+struct http_parser_request *request = http_parser_init();
+
+// Assign userdata into the request
+// Use it to track whatever you need
+request->udata = (void*)...;
+
+// Attach a function
+
+// Stored http message
+char *message =
+ "GET / HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "\r\n"
+;
+
+// Passing network data into it
+http_parser_request_data(request, message, strlen(message));
+```
diff --git a/src/http-parser.c b/src/http-parser.c
@@ -32,9 +32,10 @@ char *http_parser_header_get(struct http_parser_request *request, char *key) {
}
void http_parser_request_free(struct http_parser_request *request) {
- if (request->body) free(request->body);
if (request->method) free(request->method);
if (request->path) free(request->path);
+ if (request->version) free(request->version);
+ if (request->body) free(request->body);
if (request->headers) http_parser_header_free(request->headers);
free(request);
}
@@ -76,9 +77,10 @@ void http_parser_request_data(struct http_parser_request *request, char *data, i
*(index) = '\0';
// Read method and path
- request->method = calloc(1, 7);
- request->path = calloc(1, 512);
- if (sscanf(request->body, "%6s %511s", request->method, request->path) != 2) {
+ request->method = calloc(1, 7);
+ request->path = calloc(1, 512);
+ request->version = calloc(1, 4);
+ if (sscanf(request->body, "%6s %511s HTTP/%3s", request->method, request->path, request->version) != 3) {
request->state = HTTP_PARSER_STATE_PANIC;
return;
}
diff --git a/src/http-parser.h b/src/http-parser.h
@@ -26,6 +26,7 @@ struct http_parser_request {
int state;
char *method;
char *path;
+ char *version;
struct http_parser_header *headers;
char *body;
void (*onRequest)(struct http_parser_event*);