What would be the easiest way to add a header to e...
# ktor
m
What would be the easiest way to add a header to every request with a value that can change when specific action is taken? (example: user logs in I get the value from server, user sends specific request, I get new value)
b
Have some http client provider that checks for your condition each time a client is requested and injects relevant headers on defaultRequest{} config block
a
Could you please describe your example in terms of HTTP requests/responses?
r
Have you tried using
DefaultRequest
plugin?
m
@Big Chungus you mean I should create new client for every header value change? Because as I understand you can't change the client config after it's been set up.
b
Well HTTPClient is meant to be disposable - so yes
m
@Aleksei Tirman [JB] Lets say user logs in and gets his id as response, now I need to send a specific header with his id as a value with every subsequent request. Now if user changes account I have new user id which I need to send as a header value.
@Rustam Siniukov I did try naive approach, having value as a variable in my httpclient class and using it in
defaultRequest
, but then I get
InvalidMutabilityException
on init.
b
To be clear, both, me and @Aleksei Tirman [JB] are talking about the same thing.
As for immutability exception, defaultRequest{} lambda is meant to be pure and immutable withing the same instance of an HTTPClient
a
Can you define some variable to refer to some storage on the file level to read the ID of a user and then send it as a header value?
Copy code
private val map = mutableMapOf<String, Int>()

fun main(): Unit = runBlocking {
    val client = HttpClient(Curl)
    map["John"] = 1

    var r = client.get<String>("<https://httpbin.org/get>") {
        header("user", map["John"].toString())
    }

    println(r)

    map["John"] = 2

    r = client.get<String>("<https://httpbin.org/get>") {
        header("user", map["John"].toString())
    }

    println(r)
}
m
@Aleksei Tirman [JB] I tested something like this:
Copy code
private var activeEnvironmentId = 0
private val client = createClient {
    ...
    defaultRequest {
        header("active-environment", activeEnvironmentId)
    }
}
but with this I got
InvalidMutabilityException
as I said before. I'll try @Big Chungus variant to clone the client every time and change its defaultRequest values, because I didn't knew that clients were easily disposable and their creation is lightweight.
r
You can use
private val activeEnvironmentId = atomic(0)
to fix
InvalidMutabilityException