Skip to content

Commit

Permalink
Add charset for some application subtypes
Browse files Browse the repository at this point in the history
  • Loading branch information
marychatte committed Jun 17, 2024
1 parent e6a3235 commit 1b1657f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
30 changes: 23 additions & 7 deletions ktor-http/common/src/io/ktor/http/FileContentType.kt
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,34 @@ private val extensionsByContentType: Map<ContentType, List<String>> by lazy {
internal fun List<ContentType>.selectDefault(): ContentType {
val contentType = firstOrNull() ?: ContentType.Application.OctetStream
return when {
contentType.match(ContentType.Text.Any) && contentType.charset() == null -> contentType.withCharset(
Charsets.UTF_8
)
contentType.match(ContentType.Text.Any) -> contentType.withCharsetUTF8IfNeeded()
contentType.match(ContentType.Image.SVG) -> contentType.withCharsetUTF8IfNeeded()
contentType.matchApplicationTypeWithCharset() -> contentType.withCharsetUTF8IfNeeded()
else -> contentType
}
}

contentType.match(ContentType.Image.SVG) && contentType.charset() == null -> contentType.withCharset(
Charsets.UTF_8
)
private fun ContentType.matchApplicationTypeWithCharset(): Boolean {
if (!match(ContentType.Application.Any)) return false

else -> contentType
return when {
match(ContentType.Application.Atom) ||
match(ContentType.Application.JavaScript) ||
match(ContentType.Application.Rss) ||
match(ContentType.Application.Xml) ||
match(ContentType.Application.Xml_Dtd)
-> true

else -> false
}
}

private fun ContentType.withCharsetUTF8IfNeeded(): ContentType {
if (charset() != null) return this

return withCharset(Charsets.UTF_8)
}

internal fun <A, B> Sequence<Pair<A, B>>.groupByPairs() = groupBy { it.first }
.mapValues { e -> e.value.map { it.second } }

Expand Down
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -1260,7 +1260,8 @@ class StaticContentTest {
val extensions = mapOf(
"js" to ContentType.Text.JavaScript,
"css" to ContentType.Text.CSS,
"svg" to ContentType.Image.SVG
"svg" to ContentType.Image.SVG,
"xml" to ContentType.Application.Xml,
)

routing {
Expand Down

0 comments on commit 1b1657f

Please sign in to comment.