【发布时间】:2016-06-14 21:49:54
【问题描述】:
我正在处理 HTTP GET 请求,我正在尝试做的事情如下:
如果请求对应一个目录并且该目录不包含index.html 文件,响应一个 HTML 页面,该页面包含指向所有直接子级的链接 目录(类似于 ls -1),以及到父目录的链接。 (一个链接到 父目录看起来像父目录)
note1:为了列出目录的内容,我使用 opendir() 和 readdir()。笔记2: – HTTP 中的链接可以使用相对路径或绝对路径。
它不工作。两个错误示例如下:
FAIL-1 获取根目录列表: 我向服务器发送了一个 HTTP 请求,然后我得到了一些 HTML。 我寻找到“/test_directory1”的链接,但找不到。 (注意:在 HTML 中包含相对路径的链接是相对于 '/' 解析的。) 但是,我确实找到了“/test_file.txt”的链接。 如何重现: 我创建了一个空目录,并在其中放置了一个 test_file.txt 文件和一个 test_directory1。 我使用 --files 选项启动了 ./httpserver。 我向 Web 服务器发送了一个 / 的 HTTP 请求,以便查看我创建的所有文件。
FAIL-2 获取子目录的目录列表: 我向服务器发送了一个 HTTP 请求,然后我得到了一些 HTML。 我寻找到“/test_directory1”的链接,但找不到。 (注意:在 HTML 中包含相对路径的链接是相对于 '/test_directory1/test_directory2/' 解析的。) 但是,我确实找到了“/test_directory1/test_directory2”的链接。 如何重现: 我创建了一个空目录并在其中放置了一个 test_directory1 目录。 然后我在 test_directory1 中放了一个 test_directory2。 然后我使用 --files 选项启动 ./httpserver。 我为 /test_directory1/test_directory2 发送了一个 HTTP 请求(路径末尾没有斜杠。 我在 test_directory2 中查找文件列表,其中应包含指向父目录 (/test_directory1/) 的链接。
/*if is directory but doesn't contain index.html, send links instead*/
struct dirent *dp;
http_start_response(fd, 200);
http_send_header(fd, "Content-Type", "text/html");
http_end_headers(fd);
while( (dp = readdir(opendir(fullPath)))!= NULL){
char * filename = malloc(256+1);
strcpy(filename, dp -> d_name);
char * linkString = malloc(256+256+18+1);
strcpy(linkString, "<<a href=\"");
strcat(linkString, filename);
strcat(linkString, "\">");
strcat(linkString, filename);
strcat(linkString, "</a></");
http_send_string(fd, linkString);
free(filename);
printf("Is directory but doesn't have index.html, so all links %s\n", linkString);
free(linkString);
}
http_send_string(fd, "<html><a href=\"../\">Parent directory</a><html>");
【问题讨论】:
-
为什么要在循环内执行 printf ?还有为什么在将标签直接打印到流中更安全时构建字符串,似乎打印输出的正确方法是
http_send_string