redirect.cc 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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([&]() {
  38. http.listen("localhost", 8080);
  39. });
  40. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  41. auto httpsThread = std::thread([&]() {
  42. https.listen("localhost", 8081);
  43. });
  44. #endif
  45. httpThread.join();
  46. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  47. httpsThread.join();
  48. #endif
  49. return 0;
  50. }