Skip to content

Instantly share code, notes, and snippets.

@dave08
Created July 10, 2018 10:26
Show Gist options
  • Save dave08/6d85dc62b70daecf6f6194e3258235f0 to your computer and use it in GitHub Desktop.
Save dave08/6d85dc62b70daecf6f6194e3258235f0 to your computer and use it in GitHub Desktop.
fun Route.coHandler(controller: suspend RoutingContext.() -> ServerResponse): Route =
handler {
launch(it.vertx().dispatcher()) {
val response = it.controller()
when (response) {
is ServerResponse.Empty ->
it.response().end()
is ServerResponse.Json ->
it.response()
.putHeader("content-type", "application/json; charset=utf-8")
.end(response.jsonString)
is ServerResponse.Error ->
it.response().apply {
statusCode = response.statusCode
statusMessage = response.message
LoggerFactory.getLogger("Response dispatcher").info(statusMessage, response.exception)
}
.putHeader("content-type", "application/json; charset=utf-8")
.end(response.message)
}
}
}
sealed class ServerResponse {
object Empty : ServerResponse()
data class Error(val statusCode: Int, val message: String, val exception: Exception? = null) : ServerResponse()
data class Json(val jsonObj: Any) : ServerResponse() {
val jsonString: String
get() = Klaxon().toJsonString(jsonObj)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment