redirect.cc 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. http.Get("/test", [](const Request & /*req*/, Response &res) {
  15. res.set_content("Test\n", "text/plain");
  16. });
  17. http.set_error_handler([](const Request & /*req*/, Response &res) {
  18. res.set_redirect("https://localhost:8081/");
  19. });
  20. // HTTPS server
  21. SSLServer https(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22. https.Get("/", [=](const Request & /*req*/, Response &res) {
  23. res.set_redirect("/hi");
  24. });
  25. https.Get("/hi", [](const Request & /*req*/, Response &res) {
  26. res.set_content("Hello World!\n", "text/plain");
  27. });
  28. https.Get("/stop", [&](const Request & /*req*/, Response & /*res*/) {
  29. https.stop();
  30. http.stop();
  31. });
  32. // Run servers
  33. auto httpThread = std::thread([&]() {
  34. http.listen("localhost", 8080);
  35. });
  36. auto httpsThread = std::thread([&]() {
  37. https.listen("localhost", 8081);
  38. });
  39. httpThread.join();
  40. httpsThread.join();
  41. return 0;
  42. }