Created
July 10, 2018 10:26
-
-
Save dave08/6d85dc62b70daecf6f6194e3258235f0 to your computer and use it in GitHub Desktop.
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
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