Skip to content

Commit

Permalink
KTOR-7278: review points fix
Browse files Browse the repository at this point in the history
  • Loading branch information
anton-erofeev committed Nov 7, 2024
1 parent bb9772a commit a98252c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
6 changes: 2 additions & 4 deletions ktor-http/common/src/io/ktor/http/ContentTypes.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,11 @@ public class ContentType private constructor(
* Checks if `this` type matches a [pattern] type taking into account placeholder symbols `*` and parameters.
*/
public fun match(pattern: ContentType): Boolean {
if (pattern.contentType != "*" && contentType != "*"
&& !pattern.contentType.equals(contentType, ignoreCase = true)) {
if (pattern.contentType != "*" && !pattern.contentType.equals(contentType, ignoreCase = true)) {
return false
}

if (pattern.contentSubtype != "*" && contentSubtype != "*"
&& !pattern.contentSubtype.equals(contentSubtype, ignoreCase = true)) {
if (pattern.contentSubtype != "*" && !pattern.contentSubtype.equals(contentSubtype, ignoreCase = true)) {
return false
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,8 @@ public data class HttpMultiAcceptRouteSelector(
return RouteSelectorEvaluation.Missing
}

val header = parsedHeaders.firstOrNull { header -> contentTypes.any { it.match(header.value) } }
val header = parsedHeaders.firstOrNull { header ->
contentTypes.any { it.isCompatibleWith(ContentType.parse(header.value)) } }
if (header != null) {
return RouteSelectorEvaluation.Success(header.quality)
}
Expand Down Expand Up @@ -661,3 +662,10 @@ internal fun evaluatePathSegmentParameter(
segmentIncrement = 1
)
}

private fun ContentType.isCompatibleWith(other: ContentType): Boolean = when {
this.contentType == "*" && other.contentSubtype == "*" -> true
this.contentSubtype == "*" && other.contentType == "*" -> true
this.contentType == "*" || this.contentSubtype == "*" -> other.match(this)
else -> this.match(other)
}
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@ class RoutingProcessingTest {
}
}

on("making request to /image with Accept */png") {
client.get("/image") {
header(HttpHeaders.Accept, ContentType.parse("*/png"))
}.let {
assertEquals(HttpStatusCode.OK, it.status)
assertEquals("Image", it.bodyAsText())
}
}

on("making request to /any with Accept image/png") {
client.get("/any") {
header(HttpHeaders.Accept, ContentType.Image.PNG)
Expand All @@ -250,6 +259,15 @@ class RoutingProcessingTest {
assertEquals("Any", it.bodyAsText())
}
}

on("making request to /any with Accept */png") {
client.get("/any") {
header(HttpHeaders.Accept, ContentType.parse("*/png"))
}.let {
assertEquals(HttpStatusCode.OK, it.status)
assertEquals("Any", it.bodyAsText())
}
}
}

@Test
Expand Down

0 comments on commit a98252c

Please sign in to comment.