Cannot serve static content with Ktor

Viewed 2162

I try to use the Route.static function to serve static files, but it doesn't work. I have tried all kinds of combinations and folders in my working directory. Now I have a css under resources/static/css, and index.html under resources/static. If I write the following I don't get served anything :

@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {

    val client = HttpClient(Apache) {}

    routing {
      static("root") {
        files("css")
        default("index.html")
      }
   }
}

I can however, from this answer : Ktor - Static content routing, write :

        resource("/", "index.html")
        resource("*", "index.html")

Then I will get index.html under resources/static. I cannot however get anything else. What am I doing wrong here ?

Ref : https://ktor.io/servers/features/static-content.html#specifying-files-and-folders

2 Answers

The most correct config for static files

static {
    staticRootFolder = File(""/*or environment.rootPath)*/) // project root dir
    files("static") // dir for all static files
}

Create a static folder next to your server.jar file and put anything there.

https://example.com/file.txt
https://example.com/css/style.css
https://example.com/images/image.png

Additionally:

tasks {
    val copyStatic = register("copyStatic", Copy::class) {
        from("$projectDir/static") {
            exclude("**/*.scss", "**/*.sass", "**/*.map")
        }
        into("${rootProject.buildDir}/static")
    }
    "build" {
        dependsOn(copyStatic)
        dependsOn(fatJar)
    }
}

Let's suppose that you have your project in the C:\ktor-project folder. If you want your Ktor server to use the following URLs and give back the content of the corresponding files below, then use the code at the bottom.

http://localhost:8080/root/main.css -> C:\ktor-project\css\main.css http://localhost:8080/root -> C:\ktor-project\index.html http://localhost:8080/root/styles.css -> C:\ktor-project\resources\static-resources\styles.css

static("/root") {
    files("css")
    default("index.html")
    resources("static-resources")
}

The resources("static-resources") line can be a better choice than the files("css") line if the given styles.css file is built by your Gradle build. Most of the times you will need only one of them.

Related