Skip to content

Instantly share code, notes, and snippets.

@anuragsoni
Created September 16, 2022 02:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anuragsoni/3680b9c30ba07ff16896490310c4fa7a to your computer and use it in GitHub Desktop.
Save anuragsoni/3680b9c30ba07ff16896490310c4fa7a to your computer and use it in GitHub Desktop.
Vert.x Web + Kotlin Coroutines
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.7.10"
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
implementation("io.vertx:vertx-web:4.3.3")
implementation("io.vertx:vertx-lang-kotlin-coroutines:4.3.3")
implementation("io.vertx:vertx-lang-kotlin:4.3.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
import io.vertx.core.Vertx
import io.vertx.ext.web.Route
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.coroutines.CoroutineVerticle
import io.vertx.kotlin.coroutines.await
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
suspend fun coroutineDemo(): String {
delay(3000)
return "Hello World"
}
public fun Route.coroutineHandler(
coroutineContext: CoroutineContext,
userHandler: suspend (RoutingContext) -> Unit
) = handler { routingContext ->
CoroutineScope(coroutineContext).launch {
try {
userHandler(routingContext)
} catch (exception: Exception) {
routingContext.fail(exception)
}
}
}
class MainVerticle() : CoroutineVerticle() {
override suspend fun start() {
val router = Router.router(vertx);
router.route("/hello").coroutineHandler(coroutineContext) { routingContext ->
val payload = coroutineDemo()
routingContext.response().send(payload)
}
vertx.createHttpServer().requestHandler(router).listen(8080).await()
}
}
fun main() {
val vertx = Vertx.vertx()
vertx.deployVerticle(MainVerticle())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment