Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ktor - Static content routing

Tags:

kotlin

ktor

I would love to understand better how Ktor is handling the routing for static content. I have the following hierarchy in my static folder (working directory):

- static
 - index.html
 - (some files)
 - static
  - css (directory)
  - js (directory)
  - (some files)

I'd like to serve all of them. So I was using directly this code in routing:

static {
  defaultResource("index.html", "static")
  resources("static")
}

Which works very well, but the issue is that it's taking the hand on all requests including my small get:

get("/smoketest"){
  call.respondText("smoke test!", ContentType.Text.Plain)
}

What would be the best to handle in general the static content in Ktor?

Here is the code

Thank you

like image 843
Vlad Avatar asked Jun 18 '18 00:06

Vlad


People also ask

What is routing in KTOR?

Routing is the core Ktor plugin for handling incoming requests in a server application. When the client makes a request to a specific URL (for example, /hello ), the routing mechanism allows us to define how we want this request to be served.

What is KTOR client?

Ktor is a client-server framework that helps us build applications in Kotlin. It is a modern asynchronous framework backed by Kotlin coroutines. Ktor can be compared to network library such as OkHttp and Retrofit. We can use Ktor to make HTTP network requests to an API to get the response back to an application.

Is KTOR open source?

Anything from microservices to multiplatform HTTP client apps in a simple way. Open Source, free, and fun!


1 Answers

I tried reproducing it locally and made it work with two different approaches.

  1. Put one of these in your static block
file("*", "index.html") // single star will only resolve the first part

file("{...}", "index.html") // tailcard will match anything
  1. Or, put the following get handler as your last route:
val html = File("index.html").readText()
get("{...}") {
     call.respondText(html, ContentType.Text.Html)
}

The {...} is a tailcard and matches any request that hasn't been matched yet.

Documentation available here: http://ktor.io/features/routing.html#path

Edit: For resources I made the following work:

fun Route.staticContent() {
    static {
        resource("/", "index.html")
        resource("*", "index.html")
        static("static") {
            resources("static")
        }
    }
}

I can't see your static files in the repository, so here is what it looks like in my project: enter image description here

like image 196
avolkmann Avatar answered Oct 16 '22 15:10

avolkmann