interceptormanager.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "core/interceptormanager.h"
  2. #include "core/config.h"
  3. #include "core/app.h"
  4. #include "core/statemanager.h"
  5. #include "module/http/request.h"
  6. #include "module/http/response.h"
  7. #include "net/http_interceptor.h"
  8. fastweb::interceptor_manager::interceptor_manager(fastweb::app* app):Interface(app)
  9. {
  10. }
  11. fastweb::interceptor_manager::~interceptor_manager()
  12. {
  13. clear();
  14. }
  15. bool fastweb::interceptor_manager::add(const std::string& pattern, const std::string& filepath)
  16. {
  17. app()->router->interceptor()->add(pattern,filepath, [&](network::http::reqpack* reqpack, const std::string& pattern,const std::string& filepath)->bool {
  18. return this->callback(reqpack, pattern, filepath);
  19. });
  20. return true;
  21. }
  22. bool fastweb::interceptor_manager::remove(const std::string& pattern)
  23. {
  24. return app()->router->interceptor()->remove(pattern);
  25. }
  26. bool fastweb::interceptor_manager::exist(const std::string& pattern)
  27. {
  28. return app()->router->interceptor()->exist(pattern);
  29. }
  30. void fastweb::interceptor_manager::clear()
  31. {
  32. if(app()->router != nullptr)
  33. app()->router->interceptor()->clear();
  34. }
  35. bool fastweb::interceptor_manager::callback(network::http::reqpack* reqpack, const std::string& pattern, const std::string& filepath)
  36. {
  37. if (ylib::file::ext(filepath) != "lua")
  38. {
  39. reqpack->response()->send_file(filepath);
  40. return false;
  41. }
  42. bool ok_continue = false;
  43. auto lua = app()->state->get();
  44. std::string exception_string;
  45. try
  46. {
  47. sol::load_result script = lua->state->load_file(app()->config->website.dir+ filepath);
  48. if (!script.valid()) {
  49. sol::error err = script;
  50. throw ylib::exception(err.what());
  51. }
  52. module::request m_request(reqpack->request());
  53. module::response m_response(reqpack->response());
  54. (*lua->state)["response"] = m_response;
  55. (*lua->state)["request"] = m_request;
  56. sol::protected_function_result result = script();
  57. if (!result.valid()) {
  58. sol::error err = result;
  59. throw ylib::exception(err.what());
  60. }
  61. ok_continue = result.get<bool>();
  62. }
  63. catch (const std::exception& e)
  64. {
  65. exception_string = e.what();
  66. if (app()->config->website.debug)
  67. LOG_ERROR("[interceptor][" + reqpack->request()->filepath() + "]: " + e.what());
  68. }
  69. lua->state->collect_garbage();
  70. app()->state->push(lua);
  71. if (exception_string.empty() == false)
  72. throw ylib::exception(exception_string);
  73. return ok_continue;
  74. }