redirect.cc 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // redirect.cc
  3. //
  4. // Copyright (c) 2019 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #include <httplib.h>
  8. #define SERVER_CERT_FILE "./cert.pem"
  9. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  10. using namespace httplib;
  11. int main(void) {
  12. // HTTP server
  13. Server http;
  14. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15. SSLServer https(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16. #endif
  17. http.Get("/test", [](const Request & /*req*/, Response &res) {
  18. res.set_content("Test\n", "text/plain");
  19. });
  20. http.set_error_handler([](const Request & /*req*/, Response &res) {
  21. res.set_redirect("https://localhost:8081/");
  22. });
  23. // HTTPS server
  24. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25. https.Get("/", [=](const Request & /*req*/, Response &res) {
  26. res.set_redirect("/hi");
  27. });
  28. https.Get("/hi", [](const Request & /*req*/, Response &res) {
  29. res.set_content("Hello World!\n", "text/plain");
  30. });
  31. https.Get("/stop", [&](const Request & /*req*/, Response & /*res*/) {
  32. https.stop();
  33. http.stop();
  34. });
  35. #endif
  36. // Run servers
  37. auto httpThread = std::thread([&]() { http.listen("localhost", 8080); });
  38. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  39. auto httpsThread = std::thread([&]() { https.listen("localhost", 8081); });
  40. #endif
  41. httpThread.join();
  42. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  43. httpsThread.join();
  44. #endif
  45. return 0;
  46. }