Stijndcl
08/05/2024, 10:53 AMtoken
parameter to every single request? I have a lot of endpoints to do and want something more scaleable. Ideally looking for something like
val client = MyClient(token = "DEFAULT_APP_TOKEN") // Token to use for all requests unless specified otherwise
client.someRequest() // Uses default token
// ...
client.withToken("SOME_USER_OAUTH_TOKEN") {
client.someRequest() // Uses user-specific token
}
Best I can think of is storing the token in a variable in the client
and temporarily modifying it, but I don't feel like that would be safe in a coroutine context where multiple requests can run at the same timeAleksei Tirman [JB]
08/05/2024, 11:10 AMAutorization
header?Stijndcl
08/05/2024, 11:13 AMStijndcl
08/05/2024, 11:14 AMStijndcl
08/05/2024, 11:14 AMAleksei Tirman [JB]
08/05/2024, 12:08 PMsuspend fun main() {
val client = HttpClient(CIO) {}
client.requestPipeline.intercept(HttpRequestPipeline.Transform) {
val tokenElement = coroutineContext[TokenContextElement]
if (tokenElement != null) {
context.header(HttpHeaders.Authorization, "Bearer ${tokenElement.token}")
}
}
val response = client.withToken("123") {
client.get("<https://httpbin.org/get>")
}
println(response.bodyAsText())
}
suspend fun HttpClient.withToken(token: String, request: suspend HttpClient.() -> HttpResponse): HttpResponse {
return withContext(TokenContextElement(token)) {
request()
}
}
class TokenContextElement(val token: String) : CoroutineContext.Element {
override val key: CoroutineContext.Key<*> get() = TokenContextElement
companion object : CoroutineContext.Key<TokenContextElement>
}
Stijndcl
08/05/2024, 1:20 PM