Skip to content

Commit 782386f

Browse files
authored
redirect (#516)
1 parent e7d481e commit 782386f

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

include/cinatra/coro_http_response.hpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,13 @@ class coro_http_response {
271271
cookies_[cookie.get_name()] = cookie;
272272
}
273273

274+
void redirect(const std::string &url, bool is_forever = false) {
275+
add_header("Location", url);
276+
is_forever == false
277+
? set_status_and_content(status_type::moved_temporarily)
278+
: set_status_and_content(status_type::moved_permanently);
279+
}
280+
274281
private:
275282
status_type status_;
276283
format_type fmt_type_;

tests/test_coro_http_server.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,32 @@ bool create_file(View filename, size_t file_size = 1024) {
146146
return true;
147147
}
148148

149+
TEST_CASE("test redirect") {
150+
coro_http_server server(1, 9001);
151+
server.set_http_handler<GET>(
152+
"/", [](coro_http_request &req, coro_http_response &resp) {
153+
resp.redirect("/test");
154+
});
155+
156+
server.set_http_handler<GET>(
157+
"/test", [](coro_http_request &req, coro_http_response &resp) {
158+
resp.set_status_and_content(status_type::ok, "redirect ok");
159+
});
160+
161+
server.async_start();
162+
163+
coro_http_client client{};
164+
auto result = client.get("http://127.0.0.1:9001/");
165+
CHECK(result.status == 302);
166+
for (auto [k, v] : result.resp_headers) {
167+
if (k == "Location") {
168+
auto r = client.get(std::string(v));
169+
CHECK(r.resp_body == "redirect ok");
170+
break;
171+
}
172+
}
173+
}
174+
149175
TEST_CASE("test multiple download") {
150176
coro_http_server server(1, 9001);
151177
server.set_http_handler<GET>(

0 commit comments

Comments
 (0)