jeremycw / httpserver.h

Single header library for writing non-blocking HTTP servers in C
MIT License
1.78k stars 143 forks source link

Apparent bug with http_request_method #36

Closed travisbrady closed 4 years ago

travisbrady commented 4 years ago

When I add a call to http_request_method to the simple example in the readme it seems to return the entire request, as opposed to just the method.

Example code:

#include <stdio.h>
#define HTTPSERVER_IMPL
#include "httpserver.h"

#define RESPONSE "Hello, World!"

void handle_request(struct http_request_s* request) {
    struct http_response_s* response = http_response_init();
    printf("test %s\n", http_request_method(request).buf);
    http_response_status(response, 200);
    http_response_header(response, "Content-Type", "text/plain");
    http_response_body(response, RESPONSE, sizeof(RESPONSE) - 1);
    http_respond(request, response);
}

int main() {
    struct http_server_s* server = http_server_init(8080, handle_request);
    http_server_listen(server);
}

Compile and execute:

$ gcc -o srv main.c
$ ./srv

After hitting in my browser it prints the following to the terminal:

test GET / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36 Edg/80.0.361.62
Sec-Fetch-Dest: document
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
ioppermann commented 4 years ago

@travisbrady http_request_method(...) returns a struct http_string_s. In the documentation it says that .buf is not \0-terminated https://github.com/jeremycw/httpserver.h/blob/79ff2d8c20a997f55d7c7f4a2e91f1d55060efa3/httpserver.h#L92-L97 It is simply a pointer into the whole request. When printing it you should only print up to .len chars.

jeremycw commented 4 years ago

Yes, @ioppermann is correct. You can print it by passing the length to printf along with the correct format string: printf("test %.*s\n", str.len, str.buf);