zio-http
zio-http copied to clipboard
Load static files
I am quite new in this library but I missing a css method, when I provide static resources I implemented this code:
case Method.GET -> !! / "js"/ file =>
val content = Source.fromFile(s"./static/js/$file").getLines.toList.mkString("\n")
Response.text(content)
case Method.GET -> !! / "css"/ file =>
val content = Source.fromFile(s"./static/js/$file").getLines.toList.mkString("\n")
Response.text(content)
case Method.GET -> !! / "html"/ file =>
val content = Source.fromFile(s"./static/js/$file").getLines.toList.mkString("\n")
Response.html(content)
It works for javascript files when I reference this file from html:
<script src="js/app.js"></script>
but this way to load static files does not work for css files, maybe I am missing the proper way to do it but it would be very nice a Response method to deliver javascript files or css files like:
Response.javascript(local-path) Response.css(local-path)
Any suggestion?
We do need a static file server.
We do need a static file server.
I have a simple static fileserver as middleware, which provides an API like that:
package example
import zio._
import zio.http._
object AppMain extends ZIOAppDefault {
val staticServeMiddleware = StaticServe.middleware(
Path.root / "images",
StaticServe
.fromDirectory("/opt/repos/os/aaa/images")
.orElse(StaticServe.fromDirectory("/opt/repos/os/aaa/assets"))
.orElse(StaticServe.fromResource)
)
val appDashboard = new AppDashboard()
val appLogin = new AppLogin(appDashboard)
val appRoutes = (
appLogin.routes ++ appDashboard.routes
)
override val run =
Server.serve(appRoutes.toHttpApp @@ staticServeMiddleware).provide(Server.default)
}
I also added checks to anticipate traversal attacks (same as in akka http):
- prevent fishy requests with ".." in path segments
- prevent serving files outside of the configured document root directory
If we want that, here is a PR: https://github.com/zio/zio-http/pull/2450