Ktor - Static content routing

后端 未结 1 1499
误落风尘
误落风尘 2021-01-12 05:09

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):



        
相关标签:
1条回答
  • 2021-01-12 05:41

    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:

    0 讨论(0)
提交回复
热议问题