Skip to content

Instantly share code, notes, and snippets.

@npryce
Last active Mar 8, 2016
Embed
What would you like to do?
Using Krouton (typesafe routing & reverse routing) with Wasabi (Sinatra-like web server library for Kotlin)
import com.natpryce.krouton.*
import io.netty.handler.codec.http.HttpMethod
import io.netty.handler.codec.http.HttpMethod.GET
import org.wasabi.app.AppServer
import org.wasabi.http.Request
import org.wasabi.http.Response
import org.wasabi.http.StatusCodes
import org.wasabi.interceptors.Interceptor
import org.wasabi.routing.RouteHandler
val hello = "hello" / string
fun main(args: Array<String>) {
var server = AppServer()
server.resource(root) {
methods(
GET by { response.redirect(hello.path("World")) }
)
}
server.resource(hello) { name ->
methods(
GET by { response.send("Hello $name!") }
)
}
server.start()
}
infix fun HttpMethod.by(handler: RouteHandler.()->Unit) = this to handler
fun RouteHandler.methods(vararg handlers: Pair<HttpMethod, RouteHandler.() -> Unit>) {
val handler = handlers.firstOrNull { it.first == request.method }?.second
if (handler != null) {
RouteHandler(request, response).handler()
} else {
response.setStatus(StatusCodes.MethodNotAllowed)
response.setAllowedMethods(handlers.map { it.first }.toTypedArray())
}
}
fun <T : Any> AppServer.resource(route: UrlScheme<T>, handler: RouteHandler.(T) -> Unit) {
intercept(object : Interceptor() {
override fun intercept(request: Request, response: Response): Boolean {
val parsed = route.parse(request.path)
if (parsed != null) {
RouteHandler(request, response).handler(parsed)
return false
} else {
return true
}
}
})
}
fun AppServer.resource(route: UrlScheme<Unit>, handler: RouteHandler.() -> Unit) {
resource(route) { unit -> handler() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment