This tool is extremely small and minimalistic, with absolutely no bells or whistles.
- Loads all static assets (e.g. images, stylesheets, scripts, etc.) into memory.
- Allows retrieval by relative path.
- Tags each asset with an appropriate Content-Type.
- Tags each asset with an ETag for efficient caching and update detection.
Add the following dependency to your build.sbt:
libraryDependencies += "io.github.sgtswagrid" %% "asset-loader" % "0.1.6"Compiled with Scala 3.8.2, with no intention to explicitly support older versions.
This example uses fake Request and Response types to illustrate the idea in a simple manner.
The details will depend on your choice of web framework (e.g. Tapir or http4s).
import io.github.sgtswagrid.assetloader.{Asset, AssetLoader}
val assetLoader = AssetLoader(assetsPath = "client/src/main/resources")
def handleRequest(request: Request): Response =
if request.path.startsWith("assets/") then
val assetOption: Option[Asset] = assetLoader.getAsset(request.path.dropLeft(7))
assetOption match
case Some(asset) => Response(asset)
case None => Response.NotFound
else
// ...Tapir is a library to describe HTTP APIs and expose them as a server. A separate connector is provided to easily create a Tapir endpoint that serves static files from asset-loader. Just add the following additional dependency:
libraryDependencies += "io.github.sgtswagrid" %% "asset-loader-tapir" % "0.1.5"Observe the following minimal example, using Netty and Cats Effect:
object Main extends ResourceApp.Forever:
val assets = AssetService(
externalPath = "assets",
internalPath = Paths.get("src/main/resources"),
)
def run(args: List[String]) =
NettyCatsServer
.io()
.flatMap: server =>
val service = server
.host("0.0.0.0")
.port("8080")
.addEndpoints(assets.serverEndpoint[IO])
Resource.make(service.start())(_.stop()).as(())