Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KTOR-6183 The "charset=UTF-8" part is automatically added to the application/json Content-Type #3719

Merged
merged 1 commit into from
Aug 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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())
}
}
}