https://kotlinlang.org logo
#ktor
Title
# ktor
m

MJegorovas

12/17/2021, 12:10 PM
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

Big Chungus

12/17/2021, 12:32 PM
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

Aleksei Tirman [JB]

12/17/2021, 1:02 PM
Could you please describe your example in terms of HTTP requests/responses?
r

Rustam Siniukov

12/18/2021, 9:48 PM
Have you tried using
DefaultRequest
plugin?
m

MJegorovas

12/20/2021, 11:34 AM
@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

Big Chungus

12/20/2021, 11:35 AM
Well HTTPClient is meant to be disposable - so yes
m

MJegorovas

12/20/2021, 11:41 AM
@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

Big Chungus

12/20/2021, 11:48 AM
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

Aleksei Tirman [JB]

12/20/2021, 11:56 AM
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

MJegorovas

12/20/2021, 2:24 PM
@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

Rustam Siniukov

12/20/2021, 2:28 PM
You can use
private val activeEnvironmentId = atomic(0)
to fix
InvalidMutabilityException
7 Views