Last active
March 8, 2016 11:22
-
-
Save npryce/b7390e01e448e3e0ef7a to your computer and use it in GitHub Desktop.
Using Krouton (typesafe routing & reverse routing) with Wasabi (Sinatra-like web server library for Kotlin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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