diff --git a/src/cpp/http/response.cpp b/src/cpp/http/response.cpp index e6a8456..5ee7925 100644 --- a/src/cpp/http/response.cpp +++ b/src/cpp/http/response.cpp @@ -31,6 +31,24 @@ Response Response::from_status(StatusCode status) { return res; } +Response Response::see_other(std::string_view destination) { + Response res(fastly::sys::http::m_static_http_response_see_other( + static_cast(destination))); + return res; +} + +Response Response::redirect(std::string_view destination) { + Response res(fastly::sys::http::m_static_http_response_redirect( + static_cast(destination))); + return res; +} + +Response Response::temporary_redirect(std::string_view destination) { + Response res(fastly::sys::http::m_static_http_response_temporary_redirect( + static_cast(destination))); + return res; +} + Response Response::with_body(Body body) && { this->set_body(std::move(body)); return std::move(*this); diff --git a/test/response_redirect.cpp b/test/response_redirect.cpp new file mode 100644 index 0000000..2be7360 --- /dev/null +++ b/test/response_redirect.cpp @@ -0,0 +1,49 @@ +#include +#include + +using namespace fastly::http; + +namespace { + +// Returns the response's `Location` header, or std::nullopt if absent. +std::optional location_of(Response &resp) { + auto header{resp.get_header("Location")}; + if (!header.has_value() || !header->has_value()) { + return std::nullopt; + } + auto value{header->value().string()}; + if (!value.has_value()) { + return std::nullopt; + } + return std::string(*value); +} + +} // namespace + +TEST_CASE("Response redirect constructors set the Location header", + "[response]") { + SECTION("Response::see_other") { + auto resp{Response::see_other("https://www.fastly.com")}; + REQUIRE(location_of(resp) == std::optional("https://www.fastly.com")); + } + + SECTION("Response::redirect") { + auto resp{Response::redirect("https://www.fastly.com")}; + REQUIRE(location_of(resp) == std::optional("https://www.fastly.com")); + } + + SECTION("Response::temporary_redirect") { + auto resp{Response::temporary_redirect("https://www.fastly.com")}; + REQUIRE(location_of(resp) == std::optional("https://www.fastly.com")); + } + + SECTION("accepts a std::string_view over a non-null-terminated buffer") { + std::string buf{"https://www.fastly.com/path-and-then-some"}; + auto resp{Response::redirect(std::string_view(buf).substr(0, 22))}; + REQUIRE(location_of(resp) == std::optional("https://www.fastly.com")); + } +} + +// Required due to https://github.com/WebAssembly/wasi-libc/issues/485 +#include +int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); }