redirect.cc 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. SSLServer https(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26. https.Get("/", [=](const Request & /*req*/, Response &res) {
  27. res.set_redirect("/hi");
  28. });
  29. https.Get("/hi", [](const Request & /*req*/, Response &res) {
  30. res.set_content("Hello World!\n", "text/plain");
  31. });
  32. https.Get("/stop", [&](const Request & /*req*/, Response & /*res*/) {
  33. https.stop();
  34. http.stop();
  35. });
  36. #endif
  37. // Run servers
  38. auto httpThread = std::thread([&]() {
  39. http.listen("localhost", 8080);
  40. });
  41. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  42. auto httpsThread = std::thread([&]() {
  43. https.listen("localhost", 8081);
  44. });
  45. #endif
  46. httpThread.join();
  47. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  48. httpsThread.join();
  49. #endif
  50. return 0;
  51. }