danneu / kog

🌶 A simple Kotlin web framework inspired by Clojure's Ring.
43 stars 4 forks source link

[Router] Support prefix mounting #22

Open danneu opened 7 years ago

danneu commented 7 years ago

Note: Need more use-case ideas before actually implementing this.

Prefix mounting matches request.paths that start with a given prefix, except that the prefix is then removed from the request.path before being passed to the mounted middleware.

In other words, the mounted middleware do not know about the prefix.


The following router unfortunately queries the filesystem for every request to see if the request hits a file in the public static assets folder.

val router = Router (serveStatic("public")) {
    get("/") { Response().text("homepage")
}

Prefix mounting would let us rewrite that router to limit the serveStatic middleware only to requests with paths that start with /assets, yet without requiring any other changes to our filesystem hierarchy or the public folder.

val router = Router {
    use("/assets", serveStatic("public")
    get("/", fun(): Handler = { Response().text("homepage") })
}

Now, a request GET /assets/img/flower.png would trigger the serveStatic middleware, yet it will look up public/img/flower.png (doesn't see the /assets prefix) and serve the file if it exists.

If serveStatic does not handle the request, then the request is passed down the chain as usual with downstream middleware/handlers seeing the prefixed route.