Skip to content

Commit

Permalink
add truncate body length option to toCurl
Browse files Browse the repository at this point in the history
  • Loading branch information
daviddenton committed Sep 23, 2018
1 parent e1709d7 commit 4330f44
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
16 changes: 8 additions & 8 deletions http4k-core/src/main/kotlin/org/http4k/core/curl.kt
Expand Up @@ -4,14 +4,14 @@ import org.http4k.appendIfNotBlank
import org.http4k.appendIfNotEmpty
import org.http4k.quoted

fun Request.toCurl(): String =
StringBuilder("curl")
.append(" -X $method")
.appendIfNotEmpty(headers, " " + headers.joinToString(" ") { """-H ${(it.first + ":" + it.second).quoted()}""" })
.appendIfNotBlank(body.toString(), " --data ${body.toString().truncated().quoted()}")
.append(" \"$uri\"")
.toString()
fun Request.toCurl(truncateBodyLength: Int = 256): String =
StringBuilder("curl")
.append(" -X $method")
.appendIfNotEmpty(headers, " " + headers.joinToString(" ") { """-H ${(it.first + ":" + it.second).quoted()}""" })
.appendIfNotBlank(body.toString(), " --data ${body.toString().truncated(truncateBodyLength).quoted()}")
.append(" \"$uri\"")
.toString()

private fun String.truncated(): String = if (length > 256)
private fun String.truncated(truncateBodyLength: Int): String = if (length > truncateBodyLength)
substring(0..127) + "[truncated]" + substring(length - 128)
else this
2 changes: 1 addition & 1 deletion http4k-core/src/test/kotlin/org/http4k/CurlTest.kt
Expand Up @@ -63,7 +63,7 @@ class CurlTest {
@Test
fun `limits the entity if it's too large`() {
val largeBody = (0..500).joinToString(" ")
val curl = org.http4k.core.Request(Method.GET, "http://httpbin.org").body(largeBody).toCurl()
val curl = Request(Method.GET, "http://httpbin.org").body(largeBody).toCurl(256)
val data = "data \"([^\"]+)\"".toRegex().find(curl)?.groupValues?.get(1)!!
assertThat(data.length, equalTo(256 + "[truncated]".length))
}
Expand Down

0 comments on commit 4330f44

Please sign in to comment.