https://kotlinlang.org logo
Title
e

Erich

10/11/2021, 4:21 PM
I’m trying to create dynamic endpoints coming from a list... I see from the docs how to add path params...
"/book/{title}" bind GET to { req -> Response.invoke(Status.OK).body(GetBookDetails(req.path("title")) }
"/author/{name}/latest" bind GET to { req -> Response.invoke(Status.OK).body(GetAllBooks(author = req.path("name")).last()) }
But I’m looking to be able to take a list of Strings at runtime and create paths dynamically (with param) for each...
["book","author","character",..., "n"]
"/book/{key}"
"/author/{key}"
"/character/{key}"
...
"/{n}/{key}"
Is this possible?
d

dave

10/11/2021, 4:22 PM
yes - it's entirely possible because we do everything programmatically. just map over the list and create the list of HTTP handler bindings then compose them
e

Erich

10/11/2021, 4:41 PM
Do you have any examples of something similar? I’m struggling with the kotlin syntax of how to get there.
d

dave

10/11/2021, 4:44 PM
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.routing.bind
import org.http4k.routing.routes

fun main() {
    val endpoints = listOf("foo", "bar").map {
        "/$it" bind GET to { req: Request -> Response(OK) }
    }
    val app = routes(*endpoints.toTypedArray())

    println(app(Request(GET, "/foo")))
    println(app(Request(GET, "/bar")))
}
e

Erich

10/11/2021, 4:44 PM
Thanks @dave… that’s very helpful