Static files¶
Baldr ships a built-in MapStaticFiles route helper that streams files from a directory tree under a URL prefix. The implementation lives in src/Baldr/Application/WebApplication.cpp (header in src/Baldr/Application/WebApplication.hpp) and is exposed as a method on WebApplication.
Registering a static-files route¶
#include <Baldr/Baldr.hpp>
#include <filesystem>
int main()
{
auto builder = skr::ApplicationBuilder().WithExtension<BaldrExtension>();
auto app = builder.Build<WebApplication>();
app->MapStaticFiles("/static", "/var/www/my_app/wwwroot");
app->Run();
}
MapStaticFiles(urlPrefix, rootPath) mounts a route group under urlPrefix that serves files under rootPath. A request to /static/css/site.css resolves to <rootPath>/css/site.css. Directories resolve to index.html when present.
Path safety¶
MapStaticFiles rejects requests whose normalised path escapes rootPath (for example /static/../etc/passwd), so it is safe to mount under a public URL prefix without further sanitisation.
MIME types¶
Content-Type is inferred from the file extension using a small built-in table. Unknown extensions fall back to application/octet-stream.
Streaming¶
Large files are streamed using IStreamingResult — see Streaming results for the underlying mechanism. The framework writes Transfer-Encoding: chunked automatically and does not buffer the whole file in memory.
OpenAPI¶
Static-file routes are intentionally not included in the OpenAPI document generated by the OpenAPI extension — they are infrastructure, not part of the application's API surface.
End-to-end example¶
See examples/StaticFiles for a runnable program that:
- Locates
wwwroot/next to the executable at runtime, falling back to the current working directory. - Mounts
/staticagainst that directory. - Serves a hand-written
index.htmlat/so users can browse the file list.
const std::filesystem::path webRoot = resolveWebRoot();
app->MapStaticFiles("/static", webRoot.string());
When not to use it¶
- For very large or rarely-changing assets, consider serving them from a CDN or object store and proxying instead.
- For authenticated content, gate the route with custom middleware before the request reaches the static-files handler.
Next steps¶
- See the Streaming results page for the underlying chunked-transfer primitive.
- Browse
examples/StaticFilesfor a runnable program.