Slide 47
Slide 47 text
install(Locations) {
}
@Suppress("MagicNumber") "# Just one-off configuration
install(Compression) {
gzip()
deflate {
priority = 10.0
minimumSize(1024) "# condition
}
}
install(DefaultHeaders) {
header("X-Engine", "Ktor") "# will send this header with each response
}
val json = createJsonInstance()
install(ContentNegotiation) {
json(json)
}
install(CallLogging) {
level = Level.INFO
format { call #$
when (val status = call.response.status() "( "Unhandled") {
HttpStatusCode.Found ") "$status: ${call.request.httpMethod.value} - " +
"${call.request.uri} [accept: '${call.request.accept()}'] ") " +
"${call.response.headers[HttpHeaders.Location]}"
else ") "$status: ${call.request.httpMethod.value} - ${call.request.uri}" +
"[accept: '${call.request.accept()}']"
}
}
}
setupStatusPages(json, logger)
setupRouting(json, BeatSourcesRegistry)
}
Features
internal fun Application.setupStatusPages(json: Json, logger: Logger) {
install(StatusPages) {
status(HttpStatusCode.NotFound) { statusCode #$
val message = generate404ErrorMessage(call.request.uri)
call.respondError(json, message, statusCode)
}
exception {
call.respondError(json, "Unauthorized", HttpStatusCode.Unauthorized)
}
exception {
call.respondError(json, "Forbidden", HttpStatusCode.Unauthorized)
}
exception { cause #$
logger.info("Unhandled exception: ${cause.message}", cause)
val errorMessage = "Error while processing the request. ${cause.message}"
call.respondError(json, errorMessage, HttpStatusCode.InternalServerError)
}
}
}