From 00a5ba3581a1508282c496a4374e061a36159184 Mon Sep 17 00:00:00 2001 From: qicosmos Date: Thu, 1 Feb 2024 19:59:46 +0800 Subject: [PATCH] redirect --- include/cinatra/coro_http_response.hpp | 7 +++++++ tests/test_coro_http_server.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/include/cinatra/coro_http_response.hpp b/include/cinatra/coro_http_response.hpp index d035a466..54a6b387 100644 --- a/include/cinatra/coro_http_response.hpp +++ b/include/cinatra/coro_http_response.hpp @@ -271,6 +271,13 @@ class coro_http_response { cookies_[cookie.get_name()] = cookie; } + void redirect(const std::string &url, bool is_forever = false) { + add_header("Location", url); + is_forever == false + ? set_status_and_content(status_type::moved_temporarily) + : set_status_and_content(status_type::moved_permanently); + } + private: status_type status_; format_type fmt_type_; diff --git a/tests/test_coro_http_server.cpp b/tests/test_coro_http_server.cpp index d3ed048b..e564d188 100644 --- a/tests/test_coro_http_server.cpp +++ b/tests/test_coro_http_server.cpp @@ -146,6 +146,32 @@ bool create_file(View filename, size_t file_size = 1024) { return true; } +TEST_CASE("test redirect") { + coro_http_server server(1, 9001); + server.set_http_handler( + "/", [](coro_http_request &req, coro_http_response &resp) { + resp.redirect("/test"); + }); + + server.set_http_handler( + "/test", [](coro_http_request &req, coro_http_response &resp) { + resp.set_status_and_content(status_type::ok, "redirect ok"); + }); + + server.async_start(); + + coro_http_client client{}; + auto result = client.get("http://127.0.0.1:9001/"); + CHECK(result.status == 302); + for (auto [k, v] : result.resp_headers) { + if (k == "Location") { + auto r = client.get(std::string(v)); + CHECK(r.resp_body == "redirect ok"); + break; + } + } +} + TEST_CASE("test multiple download") { coro_http_server server(1, 9001); server.set_http_handler(