response *make_response(request *req) { strlist *filedata; char *html, *path = req->path; response *resp = response_new(); response_set_status_code(resp, 200); response_set_content_type(resp, "text/html"); if (req->method == GET || req->method == POST) { INFO("Requested path %s\n", path); if (path[0] == '/') path = &path[1]; filedata = readfile(path); if (!filedata) { WARN("Could not open file, generating 404...\n"); return make_404_response(); } html = strlist_to_string(filedata); response_set_body(resp, html); free(html); } return resp; }
response *make_404_response() { char *path = "404.html", *html; response *resp = response_new(); strlist *filedata = strlist_new(); response_set_status_code(resp, 404); response_set_content_type(resp, "text/html"); html = "<html><head><title>Not Found</title></head><body> \ <h1>404!</h1><br>Sorry, the object you requested was not found. \ </body><html>"; filedata = readfile(path); if (filedata) { html = strlist_to_string(filedata); } //INFO("Read HTML:\n%s", html); response_set_body(resp, html); //INFO("Generated response:\n"); //IFINFO(response_write(resp, STDOUT_FILENO)); return resp; }
uint8_t test_response_write ( ) { Response *response = response_create(0); response->write = test_write; response_write(response, (uint8_t *) "Hello"); check((response->headers_sent == 1), "headers are sent"); check((response->code == 200), "response code is set to 200"); const char *expected = "HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\nHello"; check((strcmp((char *) write_buffer, expected) == 0), "output is correct"); reset_write(); response = response_create(0); response->write = test_write; check((response->headers_sent == 0), "response_create returns a clean response"); response_set_content_type(response, (uint8_t *) "test/foo"); check((strcmp((char *) response->content_type, "test/foo") == 0), "the content_type is set correctly"); response_write(response, (uint8_t *) "Hello"); check((response->headers_sent == 1), "headers are sent"); check((response->code == 200), "response code is set to 200"); const char *expected2 = "HTTP/1.1 200 OK\r\nContent-type: test/foo\r\n\r\nHello"; check((strcmp((char *) write_buffer, expected2) == 0), "output is correct"); reset_write(); response = response_create(0); response->write = test_write; response->code = 404; check((response->code == 404), "the response code is set correctly"); response_write(response, (uint8_t *) "Hello"); check((response->headers_sent == 1), "headers are sent"); check((response->code == 404), "response code is still set to 404"); const char *expected3 = "HTTP/1.1 404 NOT FOUND\r\nContent-type: text/html\r\n\r\nHello"; check((strcmp((char *) write_buffer, expected3) == 0), "output is correct"); done(); }