How to Run Ktor Embedded Server from Code - kotlin

I've written a simple Ktor server that processes a JSON payload from an incoming POST request. Now, I want to spawn this server from another application, and after processing the request, shut it down.
So the first problem I need to solve is: how do I spawn the Ktor server from some other 'driver' Kotlin code? All the tutorials I've found online are 1-2 years old, and are apparently using an older version of Ktor, where the main class looks like this:
fun main(args: Array<String>) {
embeddedServer(Netty, 8080) {
routing {
get("/") {
call.respondText("Hello from Kotlin Backend", ContentType.Text.Html)
}
}
}.start(wait = true)
}
It's easy to see that one can just run the embeddedServer(Netty, 8080) { ... }.start(wait = true) from wherever they want, to spawn the server. But I downloaded the Ktor plugin for IntelliJ IDEA yesterday, and it seems things have changed lately. This is what the new main class looks like:
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
#Suppress("unused") // Referenced in application.conf
#kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(ContentNegotiation) {
gson {
}
}
routing {
get("/") {
call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
}
get("/json/gson") {
call.respond(mapOf("hello" to "world"))
}
}
}
Now, the Application.module(...) function takes care of setting up the routing and stuff, while the actual running of the server is done internally by io.ktor.server.netty.EngineMain.main(args). Also, properties like the port number are referenced from the application.conf file, and I'm not quite sure how it figures out where to find that application.conf file.
I have been able to run this Ktor server using gradlew. I also understand that it is possible to export it as an executable jar and run it (as explained here). But I can't find out how to run it from code. Any suggestions?
Edit: And it would be nice if I could set the port number from the driver code.

Related

heroku deploy issue says ktor env

i got the same problem every time i try to deploy to heruko
https://prnt.sc/IeH3wooTqqAj
a screenshot from the terminal
1- https://prnt.sc/fqpj3f2lQTz8
2- https://prnt.sc/-710l_bznc2B
this is my application.kt
fun main() {
embeddedServer(Netty, port = 8087, host = "0.0.0.0") {
module {
module()
}
}.start(wait = true)
}
Suppress("unused")
fun Application.module() {
configureKoin()
configureAuth()
configureRouting()
configureSerialization()
configureMonitoring()
configureSession()
}
Prockfile
web: build/install/com.example.googleauth/bin/com.example.googleauth
worker: python scheduler.py
every thing is uptodate and i also add the Config Vars on heroku setting
i also tryed the embedded way and also the engin way same issue

How to list configured routes in Ktor

I am setting up a project with multiple modules that contain different versions of api.
To verify correct route configuration I would like to print configured routes to application log like it is done in spring framework.
Is it possible and what should I use for that?
You can do it by recursively traversing routes starting from the root all the way down the tree and filtering in only ones with the HTTP method selector. This solution is described here.
fun Application.module() {
// routing configuration goes here
val root = feature(Routing)
val allRoutes = allRoutes(root)
val allRoutesWithMethod = allRoutes.filter { it.selector is HttpMethodRouteSelector }
allRoutesWithMethod.forEach {
println("route: $it")
}
}
fun allRoutes(root: Route): List<Route> {
return listOf(root) + root.children.flatMap { allRoutes(it) }
}
Please note that the code above must be placed after the routing configuration.

Unable to perform get request in ktor framework

I am new to ktor and trying to create api in it.As I have downloaded project from ktor.io and opened it inside IntelliJ idea community edition then run button is showing disabled and when I am running it on right clicking on application.kt file and clicking on run application option.Its showing:
ktor.application - Responding at http://0.0.0.0:8080
When I am going to this link on webpage it is showing:
The web page at http://0.0.0.0:8080/ might be temporarily down or it may have moved permanently to a new web address.
Even if I have get route defined below is my code:
Application.kt
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureRouting()
}.start(wait = true)
}
Routing.kt
fun Application.configureRouting() {
// Starting point for a Ktor app:
routing {
get("/") {
call.respondText("Hello World!")
}
}
}
Someone let me know What is an issue and how can I resolve it.

How can I make a ktor netty server use a CachedThreadPool to process requests?

Using ktor (1.4, can upgrade if needed) for a server side application, vanilla initialization:
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
...
fun Application.module() {
... stuff
}
I would like the underlying Netty engine to use a CachedThreadPool to process requests. Quite a few of my requests take substantial time to process (e.g. running long queries against a database), which I assume will block the thread processing the request and potentially make the server unresponsive.
How do I do that? Any other options? Do I need to make other changes (e.g. to the coroutine dispatchers) to make sure this has the desired effect?
I think it should be something like this
val env: ApplicationEngineEnvironment = ....
val server = embeddedServer(Netty, env) {
configureBootstrap = {
group(NioEventLoopGroup(..., CachedThreadPool(..)))
}
}
server.start(wait = true)

java.lang.UnsupportedOperationException: Packages and file facades are not yet supported in Kotlin reflection

When starting a basic Ktor app, I get:
Exception in thread "main" java.lang.UnsupportedOperationException: Packages and file facades are not yet supported in Kotlin reflection. Meanwhile please use Java reflection to inspect this class: class com.example.ApplicationKt
at kotlin.reflect.jvm.internal.KClassImpl.reportUnresolvedClass(KClassImpl.kt:301)
at kotlin.reflect.jvm.internal.KClassImpl.access$reportUnresolvedClass(KClassImpl.kt:43)
at kotlin.reflect.jvm.internal.KClassImpl$Data$descriptor$2.invoke(KClassImpl.kt:53)
at kotlin.reflect.jvm.internal.KClassImpl$Data$descriptor$2.invoke(KClassImpl.kt:44)
at kotlin.reflect.jvm.internal.ReflectProperties$LazySoftVal.invoke(ReflectProperties.java:92)
at kotlin.reflect.jvm.internal.ReflectProperties$Val.getValue(ReflectProperties.java:31)
at kotlin.reflect.jvm.internal.KClassImpl$Data.getDescriptor(KClassImpl.kt)
at kotlin.reflect.jvm.internal.KClassImpl$Data$objectInstance$2.invoke(KClassImpl.kt:106)
at kotlin.reflect.jvm.internal.ReflectProperties$LazyVal.invoke(ReflectProperties.java:62)
at kotlin.reflect.jvm.internal.ReflectProperties$Val.getValue(ReflectProperties.java:31)
at kotlin.reflect.jvm.internal.KClassImpl$Data.getObjectInstance(KClassImpl.kt)
at kotlin.reflect.jvm.internal.KClassImpl.getObjectInstance(KClassImpl.kt:239)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createModuleContainer(ApplicationEngineEnvironmentReloading.kt:328)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.executeModuleFunction(ApplicationEngineEnvironmentReloading.kt:317)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:275)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:127)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:247)
at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:106)
at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:18)
at io.ktor.server.engine.ApplicationEngine$DefaultImpls.start$default(ApplicationEngine.kt:52)
at io.ktor.server.netty.EngineMain.main(EngineMain.kt:17)
at com.example.ApplicationKt.main(Application.kt:10)
The app is just:
fun main(args: Array<String>): Unit = EngineMain.main(args)
fun Application.demoModule() {
routing {
get("/") {
call.respondText("Hello ${call.parameters["name"]}")
}
}
}
I just noticed the file resources.application.conf had an issue.
It had the wrong module name. I changed com.example.ApplicationKt.module to com.example.ApplicationKt.demoModule:
ktor {
deployment {
port = 8080
port = ${?PORT}
}
application {
modules = [ com.example.ApplicationKt.demoModule ]
}
}
What's annoying is that the error help says nothing about it.