Skip to content

Commit

Permalink
KTOR-6183 The "charset=UTF-8" part is automatically added to the `app…
Browse files Browse the repository at this point in the history
…lication/json` Content-Type (#3719)

(cherry picked from commit 240d032)
  • Loading branch information
rsinukov authored and e5l committed Aug 30, 2023
1 parent 0734151 commit e56b8bd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ public suspend fun ApplicationCall.respondBytesWriter(
* If [contentType] is `null`, it tries to fetch an already set "Content-Type" response header.
* If the header is not available, `text/plain` is used. If [contentType] is specified, it uses it.
*
* Additionally, if a charset is not set for a content type, it appends `; charset=UTF-8` to the content type.
* Additionally, if a content type is `Text` and a charset is not set for a content type,
* it appends `; charset=UTF-8` to the content type.
*/
public fun ApplicationCall.defaultTextContentType(contentType: ContentType?): ContentType {
val result = when (contentType) {
Expand All @@ -204,10 +205,11 @@ public fun ApplicationCall.defaultTextContentType(contentType: ContentType?): Co
}
} ?: ContentType.Text.Plain
}

else -> contentType
}

return if (result.charset() == null) {
return if (result.charset() == null && result.match(ContentType.Text.Any)) {
result.withCharset(Charsets.UTF_8)
} else {
result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
package io.ktor.tests.server.http

import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import io.ktor.util.reflect.*
import io.ktor.utils.io.charsets.*
import kotlin.test.*

@Suppress("DEPRECATION")
Expand Down Expand Up @@ -69,4 +71,25 @@ class RespondFunctionsTest {
client.get("/respond")
client.get("/respond-with-status")
}

@Test
fun testRespondWithText() = testApplication {
routing {
get("json") {
call.respondText("Hello", contentType = ContentType.Application.Json)
}
get("text") {
call.respondText("Hello", contentType = ContentType.Text.Plain)
}
}

client.get("/json").let {
assertEquals("Hello", it.bodyAsText())
assertEquals(ContentType.Application.Json, it.contentType())
}
client.get("/text").let {
assertEquals("Hello", it.bodyAsText())
assertEquals(ContentType.Text.Plain.withCharset(Charsets.UTF_8), it.contentType())
}
}
}

0 comments on commit e56b8bd

Please sign in to comment.