diff --git a/src/main/kotlin/daikon/HttpResponse.kt b/src/main/kotlin/daikon/HttpResponse.kt index c60a985..c0d3455 100644 --- a/src/main/kotlin/daikon/HttpResponse.kt +++ b/src/main/kotlin/daikon/HttpResponse.kt @@ -14,6 +14,11 @@ class HttpResponse(private val response: HttpServletResponse) : Response { return writer.toString() } + override fun redirect(path: String, status: Int) { + status(status) + header("Location", path) + } + override fun content(type: String) { response.contentType = type } diff --git a/src/main/kotlin/daikon/Response.kt b/src/main/kotlin/daikon/Response.kt index 1d88597..62d4a91 100644 --- a/src/main/kotlin/daikon/Response.kt +++ b/src/main/kotlin/daikon/Response.kt @@ -1,9 +1,12 @@ package daikon +import org.eclipse.jetty.http.HttpStatus.MOVED_TEMPORARILY_302 + interface Response { fun write(text: String) fun status(code: Int) fun content(type: String) fun header(name: String, value: String) fun body(): String + fun redirect(path: String, status: Int = MOVED_TEMPORARILY_302) } \ No newline at end of file diff --git a/src/test/kotlin/daikon/ResponseTest.kt b/src/test/kotlin/daikon/ResponseTest.kt index c7c9a20..7a95d6d 100644 --- a/src/test/kotlin/daikon/ResponseTest.kt +++ b/src/test/kotlin/daikon/ResponseTest.kt @@ -3,6 +3,8 @@ package daikon import daikon.Localhost.get import daikon.Localhost.post import org.assertj.core.api.Assertions.assertThat +import org.eclipse.jetty.http.HttpStatus.CREATED_201 +import org.eclipse.jetty.http.HttpStatus.MOVED_PERMANENTLY_301 import org.junit.jupiter.api.Test class ResponseTest { @@ -10,9 +12,9 @@ class ResponseTest { @Test fun `status code`() { HttpServer() - .any("/") { _, res -> res.status(201) } + .any("/") { _, res -> res.status(CREATED_201) } .start().use { - assertThat(get("/").statusCode).isEqualTo(201) + assertThat(get("/").statusCode).isEqualTo(CREATED_201) } } @@ -49,4 +51,24 @@ class ResponseTest { assertThat(body).isEqualTo("Hi Bob") } } + + @Test + fun `redirect to relative path`() { + HttpServer() + .any("/foo") { _, res -> res.redirect("/bar", MOVED_PERMANENTLY_301) } + .any("/bar") { _, res -> res.write("Hello") } + .start().use { + assertThat(get("/foo").text).isEqualTo("Hello") + } + } + + @Test + fun `redirect to absolute path`() { + HttpServer() + .any("/foo") { _, res -> res.redirect("http://localhost:4545/bar") } + .any("/bar") { _, res -> res.write("Hello") } + .start().use { + assertThat(get("/foo").text).isEqualTo("Hello") + } + } } \ No newline at end of file