Hi, I am looking to write a plugin (an interceptor...
# ktor
r
Hi, I am looking to write a plugin (an interceptor in retrofit). I need to add an etag if it exists in the local db, to the request and then store the etag from the response header for use next time. Any examples of how i can achieve this? The KTor documentation is not very helpful (and has. broken link).
a
You can intercept the
HttpSendPipeline
to append the ETag header to a request and the
HttpReceivePipeline
to store a header value to from a response.
Copy code
import io.ktor.client.*
import io.ktor.client.engine.apache.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*

suspend fun main() {
    val client = HttpClient(Apache)

    client.sendPipeline.intercept(HttpSendPipeline.Before) {
        // Get header value from a DB
        context.headers.append(HttpHeaders.ETag, "header-value")
    }

    client.receivePipeline.intercept(HttpReceivePipeline.Before) {
        val etag = context.response.etag()
        if (etag != null) {
            // Store E-Tag in a DB
        }
    }

    val r = client.get<String>("<https://httpbin.org/get>")
    println(r)
}
­čÖî 1