END_TEST START_TEST(test_mg_get_builtin_mime_type) { ck_assert_str_eq(mg_get_builtin_mime_type("x.txt"), "text/plain"); ck_assert_str_eq(mg_get_builtin_mime_type("x.html"), "text/html"); ck_assert_str_eq(mg_get_builtin_mime_type("x.HTML"), "text/html"); ck_assert_str_eq(mg_get_builtin_mime_type("x.hTmL"), "text/html"); ck_assert_str_eq(mg_get_builtin_mime_type("/abc/def/ghi.htm"), "text/html"); ck_assert_str_eq(mg_get_builtin_mime_type("x.unknown_extention_xyz"), "text/plain"); }
// Satisfies the HTTP request from memory, or returns a 404 error. The // filesystem is never touched. // Ideally we'd use Mongoose's open_file callback override to implement file // serving from memory instead, but that method provides no way to disable // caching or display directory index documents. static void serve_file_from_memory_or_404(struct mg_connection *connection) { const struct mg_request_info *request_info = mg_get_request_info(connection); const char *uri = request_info->uri; // If the root of the server is requested, display the index instead. if (strlen(uri) < 2) { uri = "/index.html"; } // Construct the file's full path relative to the document root. const int max_path = 2048; char file_path[max_path]; size_t path_length = strlen(uri) + strlen(document_root) + 1; const char *file = NULL; size_t file_size = 0; if (path_length < max_path) { snprintf(file_path, path_length, "%s%s", document_root, uri); file = get_file(file_path, &file_size); } if (file) { // We've located the file in memory. Serve it with headers to disable // caching. mg_printf(connection, "HTTP/1.1 200 OK\r\n" "Cache-Control: no-cache\r\n" "Content-Type: %s\r\n" "Content-Length: %lu\r\n" "Connection: close\r\n\r\n", mg_get_builtin_mime_type(file_path), file_size); mg_write(connection, file, file_size); } else { // The file doesn't exist in memory. mg_printf(connection, "HTTP/1.1 404 Not Found\r\n" "Cache-Control: no-cache\r\n" "Content-Type: text/plain; charset=utf-8\r\n" "Content-Length: 25\r\n" "Connection: close\r\n\r\n" "Error 404: File not found"); } }