Search code examples
haskellscotty

Match nested subdirectories with a Scotty RoutePattern


I'm serving some static files with my Scotty webserver. They can also be located in subdirectories. My current approach looks like this:

get "/:fileName" $ do
    fileName <- param "fileName"
    file $ pathToStaticFiles </> fileName

get "/:dirName/:fileName" $ do
    dirName <- param "dirName"
    fileName <- param "fileName"
    file $ pathToStaticFiles </> dirName </> fileName

get "/:dirName1/:dirName2/:fileName" $ do
    dirName1 <- param "dirName1"
    dirName2 <- param "dirName2"
    fileName <- param "fileName"
    file $ pathToStaticFiles </> dirName1 </> dirName2 </> fileName

....

Is there a possibility to match paths with different directory nesting depth using only one single pattern?


Solution

  • Scotty has several other route patterns on top of the default one (which is called capture). Those can be found in the documentation.

    regex seems to be exactly what you want. Here is the example from the documentation :

    get (regex "^/f(.*)r$") $ do
       path <- param "0"
       cap <- param "1"
       text $ mconcat ["Path: ", path, "\nCapture: ", cap]
    

    For your use case, it'd be a matter of catching the whole path, splitting on "/" and folding the resulting list with </>.