https://kotlinlang.org logo
Title
s

s4nchez

03/27/2020, 10:18 AM
@sahil Lone There's no need to define the
/tokens
path twice. This should work:
class TokensRouter(private val tokensCommandHandler: TokensCommandHandler) {
    operator fun invoke(): RoutingHttpHandler =
        ServerFilters.Cors(CorsPolicy.UnsafeGlobalPermissive).then(routes(
            "/tokens" bind <http://Method.POST|Method.POST> to tokensCommandHandler::invoke
        ))
}
Here's a simplified self-contained example:
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.I_M_A_TEAPOT
import org.http4k.core.then
import org.http4k.filter.CorsPolicy
import org.http4k.filter.ServerFilters
import org.http4k.routing.bind
import org.http4k.routing.routes

fun main() {
    val app = ServerFilters.Cors(CorsPolicy.UnsafeGlobalPermissive).then(routes(
        "/tokens" bind <http://Method.POST|Method.POST> to { Response(I_M_A_TEAPOT).body("ok") }
    ))

    val request = Request(Method.OPTIONS, "/tokens")
    val response = app(request)
    println(response)

    val postRequest = Request(<http://Method.POST|Method.POST>, "/tokens")
    val postResponse = app(postRequest)
    println(postResponse)
}
s

sahil Lone

03/27/2020, 10:20 AM
this binds the cors to whoel application which I dont want, I want it for just one endpoint
As far as I understand the routes are invoked in order they are defined and If I dont put path to the CORS filter then all endpoint will get CORS enabled
DO u know how can I debug this matching logic ?
s

s4nchez

03/27/2020, 10:36 AM
The only (not great way) of debugging is stepping and seeing what
org.http4k.routing.Router#match
is doing.
For you particular issue, you can mix cors and non-cors route with something like:
val corsRoute = routes("/{:.*}" bind <http://Method.POST|Method.POST> to { Response(I_M_A_TEAPOT).body("ok") })
        .with(ServerFilters.Cors(CorsPolicy.UnsafeGlobalPermissive))

    val app = routes(
        "/bob" bind Method.GET to { Response(ACCEPTED) },
        "/tokens" bind corsRoute)

    println(app(Request(Method.GET, "/bob")))
    println(app(Request(Method.OPTIONS, "/bob")))

    println(app(Request(Method.OPTIONS, "/tokens")))
    println(app(Request(<http://Method.POST|Method.POST>, "/tokens")))
s

sahil Lone

03/27/2020, 10:39 AM
I cors router will not work like u defined as OPTIONS request will not be caught
s

s4nchez

03/27/2020, 10:40 AM
The only 404 you'll get on the above is for
/bob
because it doesn't undertand OPTIONS
s

sahil Lone

03/27/2020, 10:43 AM
The issue in my earlier solution is because of /tokens appearing two times
otherwise the solution is valid as well
@s4nchez Thank you so much, your solution actually pointe to the underlying problem
s

s4nchez

03/27/2020, 10:45 AM
Excellent. Glad I could help 🙂