4

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.

laserpants
  • 43
  • 4

2 Answers2

2
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.

Carl
  • 26,500
  • 4
  • 65
  • 86
1

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
stepcut
  • 1,502
  • 8
  • 10