Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load static files #2380

Open
gvlpedro opened this issue Aug 11, 2023 · 2 comments
Open

Load static files #2380

gvlpedro opened this issue Aug 11, 2023 · 2 comments
Labels
enhancement New feature or request

Comments

@gvlpedro
Copy link

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?

@gvlpedro gvlpedro added the enhancement New feature or request label Aug 11, 2023
@jdegoes
Copy link
Member

jdegoes commented Aug 17, 2023

We do need a static file server.

@TomTriple
Copy link
Contributor

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: #2450

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants