1
0

http_page.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include "http_page.h"
  2. #include "hdir.h"
  3. #define AUTOINDEX_FILENAME_MAXLEN 50
  4. void make_http_status_page(http_status status_code, std::string& page) {
  5. char szCode[8];
  6. snprintf(szCode, sizeof(szCode), "%d ", status_code);
  7. const char* status_message = http_status_str(status_code);
  8. page += R"(<!DOCTYPE html>
  9. <html>
  10. <head>
  11. <title>)";
  12. page += szCode; page += status_message;
  13. page += R"(</title>
  14. </head>
  15. <body>
  16. <center><h1>)";
  17. page += szCode; page += status_message;
  18. page += R"(</h1></center>
  19. <hr>
  20. </body>
  21. </html>)";
  22. }
  23. void make_index_of_page(const char* dir, std::string& page, const char* url) {
  24. std::list<hdir_t> dirs;
  25. listdir(dir, dirs);
  26. char c_str[1024] = {0};
  27. snprintf(c_str, sizeof(c_str), R"(<!DOCTYPE html>
  28. <html>
  29. <head>
  30. <title>Index of %s</title>
  31. </head>
  32. <body>
  33. <h1>Index of %s</h1>
  34. <hr>
  35. <pre>
  36. )", url, url);
  37. page += c_str;
  38. for (auto& item : dirs) {
  39. if (item.name[0] == '.' && item.name[1] == '\0') continue;
  40. int len = strlen(item.name) + (item.type == 'd');
  41. // name
  42. snprintf(c_str, sizeof(c_str), "<a href=\"%s%s\">%s%s</a>",
  43. item.name,
  44. item.type == 'd' ? "/" : "",
  45. len < AUTOINDEX_FILENAME_MAXLEN ? item.name : std::string(item.name, item.name+AUTOINDEX_FILENAME_MAXLEN-4).append("...").c_str(),
  46. item.type == 'd' ? "/" : "");
  47. page += c_str;
  48. if (strcmp(item.name, "..") != 0) {
  49. // mtime
  50. struct tm* tm = localtime(&item.mtime);
  51. snprintf(c_str, sizeof(c_str), "%04d-%02d-%02d %02d:%02d:%02d ",
  52. tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
  53. page += std::string(AUTOINDEX_FILENAME_MAXLEN - len, ' ');
  54. page += c_str;
  55. // size
  56. if (item.type == 'd') {
  57. page += '-';
  58. }
  59. else {
  60. float hsize;
  61. if (item.size < 1024) {
  62. snprintf(c_str, sizeof(c_str), "%lu", item.size);
  63. }
  64. else if ((hsize = item.size/1024.0f) < 1024.0f) {
  65. snprintf(c_str, sizeof(c_str), "%.1fK", hsize);
  66. }
  67. else if ((hsize /= 1024.0f) < 1024.0f) {
  68. snprintf(c_str, sizeof(c_str), "%.1fM", hsize);
  69. }
  70. else {
  71. hsize /= 1024.0f;
  72. snprintf(c_str, sizeof(c_str), "%.1fG", hsize);
  73. }
  74. page += c_str;
  75. }
  76. }
  77. page += "\r\n";
  78. }
  79. page += R"(</pre>
  80. <hr>
  81. </body>
  82. </html>)";
  83. }