Question

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.

Was it helpful?

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.

OTHER TIPS

This is pretty close already:

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

You just need an extra nested msum:

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

As someone else suggested you can also use <|> or mplus or other functions related to Alternative and MonadPlus.

  • jeremy
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top