About
How to server a static website with vertx
Default Configuration
- Root directory: The default static file directory is called webroot
- Cache 1): cache-control is set to max-age=86400 (controlled by setMaxAgeSeconds)
Cache
When Vert.x finds a resource on the classpath for the first time it extracts it and caches it in a temporary directory on disk so it doesn’t have to do this each time.
By default, Vert.x will cache files that are served from the classpath into a file on disk in a sub-directory of a directory called .vertx in the working directory
In development this can cause a problem, as if you update your static content while the server is running, the cached file will be served not the updated file.
To disable file caching you can provide your vert.x options the property fileResolverCachingEnabled to false. For backwards compatibility it will also default that value to the system property vertx.disableFileCaching. E.g. you could set up a run configuration in your IDE to set this when running your main class.
Code
Static Handler
From a router
router.get().handler(
StaticHandler
.create()
.setCachingEnabled(false)
.setWebRoot("private"));
Webroot search:
- Static content outside the jar:
- Relative path: working directory/webroot
- Absolute path
- Static content inside the jar:
- java/main/webroot
Manual Handler
- The whole file
vertx.createHttpServer().requestHandler(request -> {
String file = "";
if (request.path().equals("/")) {
file = "index.html";
} else if (!request.path().contains("..")) {
file = request.path();
}
request.response().sendFile("web/" + file);
}).listen(8080);
- Just a portion
vertx.createHttpServer().requestHandler(request -> {
long offset = 0;
try {
offset = Long.parseLong(request.getParam("start"));
} catch (NumberFormatException e) {
// error handling...
}
long end = Long.MAX_VALUE;
try {
end = Long.parseLong(request.getParam("end"));
} catch (NumberFormatException e) {
// error handling...
}
request.response().sendFile("web/mybigfile.txt", offset, end);
}).listen(8080);