From 3a31c46c969067a1684de7f4a6611961f1fd69dd Mon Sep 17 00:00:00 2001 From: Aki Date: Sat, 2 May 2020 15:47:02 +0200 Subject: Moved method parsing to a separate function --- http.c | 41 +++++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/http.c b/http.c index 6eda100..aa0e8dc 100644 --- a/http.c +++ b/http.c @@ -62,13 +62,29 @@ int respond_with_body(const int fd, const enum status status, const char * body) return send(fd, body, strlen(body), 0); } -/// -/// \param fd -/// \param request -/// \return +/// Compares the `buffer` to list of supported methods. +/// \param buffer Pointer to the first byte of request +/// \return One of supported methods or METHOD_INVALID +enum method parse_method(const char * buffer) +{ + for (int i = 0; i < NUMBER_OF_METHODS; ++i) + { + if (0 == strncmp(method_str[i], buffer, strlen(method_str[i]))) + { + return i; + } + } + + return METHOD_INVALID; +} + +/// Receives and parses request or part of it from a client. +/// \param fd Client socket +/// \param request Parser output and state +/// \return Number of bytes parsed or -1 if an error occurred int parse_request(const int fd, struct request * const request) { - char buffer[10240]; + char buffer[10240] = {0}; int length = recv(fd, buffer, 10240, 0); @@ -82,18 +98,11 @@ int parse_request(const int fd, struct request * const request) return -1; // TODO: Handle errors properly } - for (int i = 0; i < NUMBER_OF_METHODS; ++i) - { - if (0 == strncmp(method_str[i], buffer, strlen(method_str[i]))) - { - request->method = i; - break; - } + request->method = parse_method(buffer); - if (NUMBER_OF_METHODS - 1 == i) - { - // TODO: 501 Not Implemented - } + if (METHOD_INVALID == request->method) + { + // TODO: 501 Not Implemented } request->body = malloc(length + 1); -- cgit v1.1