Skip to content

Commit

Permalink
KTOR-4990 Fix duplication of default headers
Browse files Browse the repository at this point in the history
  • Loading branch information
rsinukov committed Oct 17, 2022
1 parent 3b7b62d commit f56bb25
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
Expand Up @@ -6,6 +6,7 @@ package io.ktor.server.plugins.defaultheaders

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.defaultheaders.DefaultHeadersConfig.*
import io.ktor.server.response.*
import io.ktor.util.*
import io.ktor.util.date.*
Expand Down Expand Up @@ -94,13 +95,15 @@ public val DefaultHeaders: RouteScopedPlugin<DefaultHeadersConfig> = createRoute

val serverHeader = "Ktor/$ktorPackageVersion"
onCallRespond { call, _ ->
headers.forEach { name, value -> value.forEach { call.response.header(name, it) } }
headers.forEach { name, value ->
if (!call.response.headers.contains(name)) value.forEach { call.response.header(name, it) }
}

if (!call.response.headers.contains(HttpHeaders.Date)) {
call.response.header(HttpHeaders.Date, calculateDateHeader())
}
if (!call.response.headers.contains(HttpHeaders.Server)) {
call.response.headers.append(HttpHeaders.Server, serverHeader)
call.response.header(HttpHeaders.Server, serverHeader)
}
}
}
Expand Up @@ -7,6 +7,7 @@ package io.ktor.tests.plugins
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.application.hooks.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
Expand Down Expand Up @@ -117,4 +118,18 @@ class DefaultHeadersTest {

assertEquals("MyServer", client.get("/").headers[HttpHeaders.Server])
}

@Test
fun testCustomServerHeaderDoesntDuplicate(): Unit = testApplication {
install(createApplicationPlugin("test") {
on(CallSetup) {
it.response.header(HttpHeaders.Server, "MyServer")
}
})
install(DefaultHeaders) {
header(HttpHeaders.Server, "MyServer1")
}

assertEquals(listOf("MyServer"), client.get("/").headers.getAll(HttpHeaders.Server))
}
}

0 comments on commit f56bb25

Please sign in to comment.