1
0

httpsServer.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "httpsServer.hpp"
  2. #include <system_error>
  3. namespace cpr {
  4. HttpsServer::HttpsServer(fs::path&& baseDirPath, fs::path&& sslCertFileName, fs::path&& sslKeyFileName) : baseDirPath(baseDirPath.make_preferred().string()), sslCertFileName(sslCertFileName.make_preferred().string()), sslKeyFileName(sslKeyFileName.make_preferred().string()) {
  5. // See https://mongoose.ws/tutorials/tls/
  6. memset(static_cast<void*>(&tlsOpts), 0, sizeof(tlsOpts));
  7. tlsOpts.cert = this->sslCertFileName.c_str();
  8. tlsOpts.certkey = this->sslKeyFileName.c_str();
  9. }
  10. std::string HttpsServer::GetBaseUrl() {
  11. return "https://127.0.0.1:" + std::to_string(GetPort());
  12. }
  13. uint16_t HttpsServer::GetPort() {
  14. // Unassigned port in the ephemeral range
  15. return 61937;
  16. }
  17. mg_connection* HttpsServer::initServer(mg_mgr* mgr, mg_event_handler_t event_handler) {
  18. mg_mgr_init(mgr);
  19. std::string port = std::to_string(GetPort());
  20. mg_connection* c = mg_http_listen(mgr, GetBaseUrl().c_str(), event_handler, this);
  21. return c;
  22. }
  23. void HttpsServer::acceptConnection(mg_connection* conn) {
  24. // See https://mongoose.ws/tutorials/tls/
  25. mg_tls_init(conn, &tlsOpts);
  26. }
  27. void HttpsServer::OnRequest(mg_connection* conn, mg_http_message* msg) {
  28. std::string uri = std::string(msg->uri.ptr, msg->uri.len);
  29. if (uri == "/hello.html") {
  30. OnRequestHello(conn, msg);
  31. } else {
  32. OnRequestNotFound(conn, msg);
  33. }
  34. }
  35. void HttpsServer::OnRequestNotFound(mg_connection* conn, mg_http_message* /*msg*/) {
  36. mg_http_reply(conn, 404, nullptr, "Not Found");
  37. }
  38. void HttpsServer::OnRequestHello(mg_connection* conn, mg_http_message* /*msg*/) {
  39. std::string response{"Hello world!"};
  40. std::string headers{"Content-Type: text/html\r\n"};
  41. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  42. }
  43. const std::string& HttpsServer::getBaseDirPath() const {
  44. return baseDirPath;
  45. }
  46. const std::string& HttpsServer::getSslCertFileName() const {
  47. return sslCertFileName;
  48. }
  49. const std::string& HttpsServer::getSslKeyFileName() const {
  50. return sslKeyFileName;
  51. }
  52. } // namespace cpr