Ana içeriğe geç

Ktor as an Application Host Envelope

In many backend applications, the web framework invades every layer of the codebase. I took a different approach: Ktor is strictly an HTTP host envelope.


What Ktor Does vs. What It Doesn't Do​

  • What Ktor Does: Listens on HTTP/2 network sockets, handles route matching, serializes JSON responses (ContentNegotiation), converts unhandled exceptions to clean HTTP errors (StatusPages), and serves static React assets.
  • What Ktor Doesn't Do: Ktor has zero knowledge of my domain models, business rules, or persistence logic.

Why: By keeping Ktor out of my core domain, I can run my entire business logic in lightning-fast unit tests or CLI scripts without starting an HTTP server or mocking framework contexts.

Here's an example of how a Ktor route simply delegates the work to a pure Kotlin domain service:

fun Route.itemRoutes(items: ItemsFacade) {
route("/api/v1/items") {
get("/{id}") {
val id = call.parameters["id"] ?: throw BadRequestException("Missing id")
val item = items.get(id) // Pure domain call
call.respond(item)
}
}
}