From 6d79b9fb1985da1cb0096b5ee38a75f21aa595ec Mon Sep 17 00:00:00 2001 From: Marco Fracassi Date: Thu, 26 Mar 2020 15:51:01 +0100 Subject: [PATCH] Fix read post parameters --- src/main/kotlin/daikon/HttpRequest.kt | 18 +++++++++++++++++- src/test/kotlin/daikon/RequestTest.kt | 20 ++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/daikon/HttpRequest.kt b/src/main/kotlin/daikon/HttpRequest.kt index ffb43a8..9e1d68b 100644 --- a/src/main/kotlin/daikon/HttpRequest.kt +++ b/src/main/kotlin/daikon/HttpRequest.kt @@ -3,6 +3,8 @@ package daikon import daikon.core.Method import daikon.core.PathParams import daikon.core.Request +import java.net.URLDecoder.decode +import java.nio.charset.StandardCharsets.UTF_8 import javax.servlet.http.HttpServletRequest class HttpRequest(private val request: HttpServletRequest) : Request { @@ -48,6 +50,20 @@ class HttpRequest(private val request: HttpServletRequest) : Request { } override fun param(name: String): String { - return request.getParameter(name) ?: pathParams.valueOf(path()).getValue(name) + return getBodyParameter(name) ?: request.getParameter(name) ?: pathParams.valueOf(path()).getValue(name) + } + + private fun getBodyParameter(name: String): String? { + if(body().isEmpty() || !hasHeader("Content-Type") || !header("Content-Type").startsWith("application/x-www-form-urlencoded")) { + return null + } + try { + return body().split("&").map { + val (key, value) = it.split("=") + key to decode(value, UTF_8.name()) + }.toMap()[name] + }catch (t: Throwable) { + return null + } } } \ No newline at end of file diff --git a/src/test/kotlin/daikon/RequestTest.kt b/src/test/kotlin/daikon/RequestTest.kt index e0d91c2..6c12cd2 100644 --- a/src/test/kotlin/daikon/RequestTest.kt +++ b/src/test/kotlin/daikon/RequestTest.kt @@ -36,6 +36,26 @@ class RequestTest { } } + @Test + fun `read param in post with empty body`() { + HttpServer() + .post("/:test") { req, res -> res.write(req.param(":test")) } + .start() + .use { + assertThat(local("/any").http.post().body).isEqualTo("any") + } + } + + @Test + fun `can read post parameters and body`() { + HttpServer() + .post("/") { req, res -> res.write("""${req.body()} - ${req.param("name")}""") } + .start() + .use { + assertThat(local("/").http.post(data = mapOf("name" to "Bob")).body).isEqualTo("name=Bob - Bob") + } + } + @Test fun headers() { HttpServer()