Skip to content

Commit

Permalink
redirect (#516)
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos authored Feb 1, 2024
1 parent e7d481e commit 782386f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
7 changes: 7 additions & 0 deletions include/cinatra/coro_http_response.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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_;
Expand Down
26 changes: 26 additions & 0 deletions tests/test_coro_http_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<GET>(
"/", [](coro_http_request &req, coro_http_response &resp) {
resp.redirect("/test");
});

server.set_http_handler<GET>(
"/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<GET>(
Expand Down

0 comments on commit 782386f

Please sign in to comment.