-1.4 C
New York
Friday, January 10, 2025

Introduction to Ktor: the HTTP server for Kotlin



Now, if we need to generate extra refined content material from that endpoint, resembling a listing of citations and their authors, we are able to transfer on to utilizing Ktor’s HTML DSL. First, we’d like two extra imports, that are already a part of the challenge as a result of we included the DSL within the generated challenge:


import io.ktor.server.html.*
import kotlinx.html.*


And we are able to generate our response like this:


routing {
  get("/") {
    name.respondHtml {
      head {
        title("Quotes")
      }
      physique {
        h1 { +"Quotes to Stay By" }
        ul {
          listOf(
            "This Thoughts is the matrix of all matter." to "Max Planck",
            "All religions, arts and sciences are branches of the identical tree." to "Albert Einstein",
            "The thoughts is all the pieces. What you assume you develop into." to "Buddha"
          ).forEach { (quote, creator) ->
       li {
         p { +quote }
         p { +"― $creator" }
       }
     }
   }
 }

This makes use of Ktor’s HTML authoring options and reveals a number of the flexibility in Kotlin’s useful syntax. The DSL features that correspond to HTML tags are simply comprehensible and we create the identical nested construction as we’d with plain HTML. Between braces, we outline the content material nested inside every tag. It may be extra markup, textual content, variables, or some mixture.

Related Articles

Latest Articles