0

For ease of app relocation I would like to serve static files from memory instead of disk in my Scotty application. I'm currently using wai-middleware-static to serve files from disk but I see that there is a wai-app-static that could do it, but it is not in the form of a Middleware.

Can I turn the wai-app-static Application into a Middleware or is there another package I am missing?

ase
  • 13,231
  • 4
  • 34
  • 46

2 Answers2

1

Middleware has the type Application -> Application. So if you want to turn someApplication into Middleware, a way you could do it is:

staticMiddleware :: Middleware
staticMiddleware = \app -> someApplication

You throw away an argument that is an Application and return the application you want, and now you have Middleware!

Probably not very useful Middleware. You may want to look at the request to figure out how to handle it? Like, some requests are going to be handled by this static server middleware, and others are going to be handled your regular server?

Maybe you could do something like this:

someMiddleware :: Middleware
someMiddleware = \app -> branchingApp

branchingApp :: Application
branchingApp req functionReqToRecieved =
  if iWantToStaticServeThis req
  then staticApp req functionReqToRecieved
  else dynamicApp req functionReqToRecieved

This is terrible code so please don't copy but I hope it gets the idea across?

An Application is a function: Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived. I want to say how to use that first argument (the request). So, instead of saying this Middleware returns this predefined application, I'm constructing my own Application, that just takes a look at the Request and decides which Application should handle it. Then it passes the arguments back to the Application.

There might be a helper function somewhere that does this for you, too, but I'm not sure.

Libby
  • 1,357
  • 12
  • 17
  • (I saw you already figured out an answer but I had this in draft so I posted anyway in case it's helpful to someone in the future.) – Libby Jan 19 '17 at 21:52
  • 1
    Thank you, this gave me some things to think about! :) – ase Jan 19 '17 at 22:18
0

I could not find what I was looking for so I made my own: https://github.com/adamse/wai-middleware-static-embedded based on wai-middleware-static.

It provides a function

static :: [(FilePath, ByteString)] -> Middleware

which serves a file if it is in the supplied list.

ase
  • 13,231
  • 4
  • 34
  • 46