Single Page Applications (SPA)
This handler provides an easy way to serve a single page application (for example a Vue.js, React, or Angular app) to your clients.
Hosting a SPA
import org.genhttp.api.content.io.ResourceTree
import org.genhttp.engine.internal.Host
import org.genhttp.modules.io.fromDirectory
import org.genhttp.modules.practices.defaults
import org.genhttp.modules.singlepageapplications.SinglePageApplication
suspend fun main() {
val tree = ResourceTree.fromDirectory("/var/html/my-webapp")
val app = SinglePageApplication.from(tree)
Host.create()
.defaults()
.handler(app)
.run()
}This example will automatically search for an index file (such as index.html) in
the specified directory and serve it to clients accessing http://localhost:8080/.
If the application is built into the resources of your project (e.g. src/main/resources/my-webapp),
serve it from the classpath with ResourceTree.fromClasspath("my-webapp") instead.
Routing
If you would like to use path based routing in your application, the server needs to
serve the SPA index for every route. This can be achieved with the serverSideRouting()
function on the SPA builder.
val app = SinglePageApplication.from(ResourceTree.fromDirectory("/var/html/my-webapp"))
.serverSideRouting()Files of the application are still served as they are - the index is returned for every request that does not match a file.