StaticWebPageController.cpp 4.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // Created by xcbosa on 2023/1/28.
  3. //
  4. #include "../processor/processor.h"
  5. #include "../webuiconf.h"
  6. #include <sys/stat.h>
  7. using namespace std;
  8. using namespace xc::processor;
  9. namespace xc::controller {
  10. ContentGeneratorDefine({
  11. if (request.getMethod() != "GET") { return false; }
  12. if (request.getURL().length() == 0) { return false; }
  13. struct stat buffer;
  14. string filePath = "html";
  15. if (request.getURL()[0] == '/') {
  16. filePath += request.getURL();
  17. } else {
  18. filePath += "/" + request.getURL();
  19. }
  20. if (stat(filePath.c_str(), &buffer) == 0) {
  21. if (S_ISREG(buffer.st_mode)) {
  22. return true;
  23. } else {
  24. for (auto file: conf::defaultFiles) {
  25. string newFilePath = filePath;
  26. if (filePath[filePath.length() - 1] == '/') {
  27. newFilePath += file;
  28. } else {
  29. newFilePath += "/" + file;
  30. }
  31. if (stat(newFilePath.c_str(), &buffer) == 0) {
  32. return S_ISREG(buffer.st_mode);
  33. }
  34. }
  35. }
  36. }
  37. return false;
  38. }, {
  39. struct stat buffer;
  40. string filePath = "html";
  41. if (request.getURL()[0] == '/') {
  42. filePath += request.getURL();
  43. } else {
  44. filePath += "/" + request.getURL();
  45. }
  46. if (stat(filePath.c_str(), &buffer) == 0) {
  47. if (S_ISREG(buffer.st_mode)) {
  48. return (ResponseData *) new BinaryResponseData(200, filePath,
  49. mimeTypeOfFile(filePath));
  50. } else {
  51. for (auto file: conf::defaultFiles) {
  52. string newFilePath = filePath;
  53. if (filePath[filePath.length() - 1] == '/') {
  54. newFilePath += file;
  55. } else {
  56. newFilePath += "/" + file;
  57. }
  58. if (stat(newFilePath.c_str(), &buffer) == 0) {
  59. if (S_ISREG(buffer.st_mode)) {
  60. return (ResponseData *) new BinaryResponseData(200, newFilePath,
  61. mimeTypeOfFile(
  62. newFilePath));
  63. }
  64. }
  65. }
  66. }
  67. }
  68. return (ResponseData *) new FileResponseData(conf::errorPage404);
  69. })
  70. ContentGeneratorDefine(return request.getURL() == "/test1", {
  71. return new TextResponseData(200, "test1 controller response");
  72. })
  73. ContentGeneratorDefine(return request.getURL() == "/test2", {
  74. return new TextResponseData(200, "test2 controller response");
  75. })
  76. }