Skip to content

Instantly share code, notes, and snippets.

@romainbsl
Last active June 3, 2019 05:27
Show Gist options
  • Save romainbsl/b21c4536a33548292edf033347c4e66c to your computer and use it in GitHub Desktop.
Save romainbsl/b21c4536a33548292edf033347c4e66c to your computer and use it in GitHub Desktop.
Ktor with Kodein controller example
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.response.respondText
import io.ktor.routing.*
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import org.kodein.di.Kodein
import org.kodein.di.generic.*
import org.kodein.di.ktor.*
import org.kodein.di.ktor.controller.*
fun main() {
embeddedServer(Netty, port = 8000, module = Application::starter).start(true)
}
fun Application.starter() {
install(Authentication) {
basic("basicAuth") {
realm = "Ktor Server"
validate { if (it.name == "superuser" && it.password == "password") UserIdPrincipal(it.name) else null }
}
}
kodein {
bind() from singleton { PublicController(instance()) }
bind() from singleton { LowerCaseController(instance()) }
bind() from singleton { UpperCaseController(instance()) }
}
install(KodeinControllerFeature)
}
class PublicController(application: Application) : KodeinController {
override val kodein by kodein { application }
override fun Routing.installRoutes() {
route("/public") {
get {
call.respondText("Hello WORLD!")
}
}
}
}
class LowerCaseController(application: Application) : KodeinController {
override val kodein by kodein { application }
override fun Routing.installRoutes() {
authenticate("basicAuth") {
route("/protected") {
get("/user/lower") {
val principal = call.principal<UserIdPrincipal>()!!
call.respondText("Hello ${principal.name.toLowerCase()}!")
}
}
}
}
}
class UpperCaseController(application: Application) : KodeinController {
override val kodein by kodein { application }
override fun Routing.installRoutes() {
authenticate("basicAuth") {
route("/protected") {
get("/user/upper") {
val principal = call.principal<UserIdPrincipal>()!!
call.respondText("Hello ${principal.name.toUpperCase()}!")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment