Conditional Headers
The ConditionalHeaders feature avoids sending the body of content if it has not changed since the last request. This is achieved by using the following headers:
- The
Last-Modifiedresponse header contains a resource modification time. For example, if the client request contains theIf-Modified-Sincevalue, Ktor will send a full response only if a resource has been modified after the given date. Note that for static files Ktor appends theLast-Modifiedheader automatically after installingConditionalHeaders. - The
Etagresponse header is an identifier for a specific resource version. For instance, if the client request contains theIf-None-Matchvalue, Ktor won’t send a full response in case this value matches theEtag. You can specify theEtagvalue when configuringConditionalHeaders.
Install ConditionalHeaders
To install the ConditionalHeaders feature, pass it to the install function in the application initialization code. This can be the main function …
1. import io.ktor.features.*
2. // ...
3. fun Application.main() {
4. install(ConditionalHeaders)
5. // ...
6. }
… or a specified module:
1. import io.ktor.features.*
2. // ...
3. fun Application.module() {
4. install(ConditionalHeaders)
5. // ...
6. }
Configure Headers
To configure ConditionalHeaders, you need to call the version function inside the install block. This function provides access to a list of resource versions for a given OutgoingContent. You can specify the required versions by using the EntityTagVersion and LastModifiedVersion class objects.
The code snippet below shows how to add a specified Etag value for CSS:
1. install(ConditionalHeaders) {
2. version { outgoingContent ->
3. when (outgoingContent.contentType?.withoutParameters()) {
4. ContentType.Text.CSS -> listOf(EntityTagVersion("123abc"))
5. else -> emptyList()
6. }
7. }
8. }
