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 18, 2022
1 parent 3b7b62d commit 413edef
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 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,20 @@ 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))
}
}
Expand Up @@ -7,10 +7,10 @@ package io.ktor.websocket
import io.ktor.util.*
import io.ktor.util.cio.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.errors.*
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import io.ktor.utils.io.errors.*
import kotlin.coroutines.*

/**
Expand Down

0 comments on commit 413edef

Please sign in to comment.