Last active
June 3, 2019 05:27
-
-
Save romainbsl/b21c4536a33548292edf033347c4e66c to your computer and use it in GitHub Desktop.
Ktor with Kodein controller example
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
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