Skip to content

Commit

Permalink
KTOR-3799 Add charset only for text/* content types (#3370)
Browse files Browse the repository at this point in the history
  • Loading branch information
rsinukov authored Feb 13, 2023
1 parent 9be89d7 commit 4431d95
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -209,4 +209,26 @@ abstract class JsonContentNegotiationTest(private val converter: ContentConverte
assertEquals(null, response.body<Wrapper?>())
}
}

@Test
fun testNoCharsetIsAdded() = testApplication {
routing {
post("/") {
assertNull(call.request.contentType().charset())
call.respond("OK")
}
}

createClient {
install(io.ktor.client.plugins.contentnegotiation.ContentNegotiation) {
register(ContentType("application", "json-patch+json"), converter)
}
}.post("/") {
val data: Wrapper? = null
contentType(ContentType("application", "json-patch+json"))
setBody(data)
}.let {
assertEquals("OK", it.bodyAsText())
}
}
}
2 changes: 1 addition & 1 deletion ktor-http/common/src/io/ktor/http/ContentTypes.kt
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ public fun ContentType.withCharset(charset: Charset): ContentType =
* if [ContentType] is not ignored
*/
public fun ContentType.withCharsetIfNeeded(charset: Charset): ContentType =
if (contentType.lowercase() == "application" && contentSubtype.lowercase() == "json") {
if (contentType.lowercase() != "text") {
this
} else {
withParameter("charset", charset.name)
Expand Down
15 changes: 15 additions & 0 deletions ktor-http/common/test/io/ktor/tests/http/ContentTypeTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package io.ktor.tests.http

import io.ktor.http.*
import io.ktor.utils.io.charsets.Charsets
import kotlin.test.*

class ContentTypeTest {
Expand Down Expand Up @@ -140,4 +141,18 @@ class ContentTypeTest {
val content = ContentType.parse(contentType)
assertEquals("text/html; charset=UTF-8", content.toString())
}

@Test
fun testNoCharsetForNonText() {
assertNull(ContentType.Audio.MP4.withCharsetIfNeeded(Charsets.UTF_8).charset())
assertNull(ContentType.Application.Json.withCharsetIfNeeded(Charsets.UTF_8).charset())
assertNull(ContentType("application", "json-patch+json").withCharsetIfNeeded(Charsets.UTF_8).charset())
}

@Test
fun testCharsetForText() {
assertEquals(Charsets.UTF_8, ContentType.Text.Any.withCharsetIfNeeded(Charsets.UTF_8).charset())
assertEquals(Charsets.UTF_8, ContentType.Text.Html.withCharsetIfNeeded(Charsets.UTF_8).charset())
assertEquals(Charsets.UTF_8, ContentType("Text", "custom").withCharsetIfNeeded(Charsets.UTF_8).charset())
}
}

0 comments on commit 4431d95

Please sign in to comment.