Hello! I'm having some issues when trying to add c...
# spring
l
Hello! I'm having some issues when trying to add custom headers to a
HttpServletResponse
within a suspend function. The approach we are using now is not good, so we would like to find a proper solution:
Copy code
@GetMapping("/users")
suspend fun getUsers(//...parameters, response: HttpServletResponse): List<UsersResource> {
    val users = userService.searchBy(//parameters)
    response.addPaginationHeaders(users.size)
    return users
}
For instance,
addPaginationHeaders
will be changed only for example purposes, as below:
Copy code
internal fun HttpServletResponse.addPaginationHeaders(size: Int) {
    val uri = ServletUriComponentBuilder.fromCurrentRequest().toUriString()
    setHeaders("X-Count", size)
    //...other params
}
So, suspend function doesn't work (throws
java.lang.IllegalStateException: No current ServletRequestAttributes
). Instead, we have to place the function body within a
runBlocking
to make it work.
Copy code
suspend fun getUsers(\\...parameters, response: HttpServletResponse) = runBlocking {
    //same code as above
}
Has anyone experienced this issue? Is there any solution besides
runBlocking
?
s
Interesting, let me have a look.
e
It seems like the servlet context isnt getting propagated from one thread to the other after the suspend function
userService.searchBy
returns
I havent looked at how spring is calling the suspend handler functions but it seems the solution would be to add the servlet context (and any other thread based contexts spring relies on eg MDC, ReactorContext[which is set automatically afaik] etc) as `ThreadContextElement`s to the coroutine, so that they are copied through all of the threads that coroutine runs on
s
Yeah likely this kind of issue
I want to try with
Mono
to see if that's Coroutines specific or not.
👍🏾 1
I am not able to reproduce the issue.
l
is this the right approach to propagate the context to he coroutine? https://blog.jdriven.com/2021/07/propagating-the-spring-securitycontext-to-your-kotlin-coroutines/
since it has a ContextHolder, sounds easier to manage states. but could not find anything looked like to servlet context
311 Views