This is an example project demonstrating how to use the Ktor-routes-codegen project to generate routing code from a routes file.
- Make sure you have Java 21 or higher installed
- Run the application:
./gradlew run- Open your browser and navigate to
http://localhost:8080
src/main/kotlin/com/example/Application.kt- Main application entry pointsrc/main/kotlin/com/example/controllers/- Controller classes that handle requestssrc/main/resources/routes- Routes definition file
- The
@GenerateRoutesannotation triggers the KSP processor at compile time - The processor reads the
routesfile and generates type-safe routing code - The generated
GeneratedRoutesclass is used in the application to configure routing
The routes file uses a simple syntax inspired by Play Framework:
# HTTP_METHOD PATH CONTROLLER.ACTION(parameters)
GET / com.example.controllers.HomeController.index()
GET /users/:id com.example.controllers.UserController.show(id: String)
When you run ./gradlew build, the KSP processor generates routing code in the build/generated/ksp/main/kotlin/
directory.
The generated GeneratedRoutes class automatically creates route handlers for each line in the routes file. For
example, the two lines above will look like this in the generated file:
class GeneratedRoutes {
fun configureRoutes(routing: Routing) {
routing.get("/") {
val controller = HomeController()
controller.index()
}
routing.get("/users/{id}") {
val controller = UserController()
val id = call.parameters["id"] ?: ""
controller.show(id)
}
}
}