Search code examples
haskellfilterrouteshappstack

Combining GET and POST parts in Happstack route filters


I'm trying to implement a simple request handler using Happstack:

main :: IO ()
main = simpleHTTP nullConf app

app :: ServerPart Response
app = msum [
             dir "hello" $ method GET  >> helloGet
           , dir "hello" $ method POST >> helloPost
           ]

How can I achieve something similar without repeating the dir "hello"?

This,

app :: ServerPart Response
app = msum [
             dir "hello" $ do
                method GET  >> helloGet
                method POST >> helloPost
           , okResponse home
           ]

will only "fall through" to the default part.


Solution

  • app :: ServerPart Response
    app = msum [
                 dir "hello" $ (method GET >> helloGet) <|> (method POST >> helloPost)
               , okResponse home
               ]
    

    .. Assuming ServerPart has the appropriate Alternative instance. If it's missing for some reason, you can replace (<|>) with mplus. The main idea here is that you're just nesting one routing combinator inside another.