Search code examples
haskellhappstack

Create a custom happstack response code


I have been trying to create a custom happstack response the 405 "Method not allowed" so if someone calls the API with a POST or PUT method they will get this response. I am new to happstack. Any ideas how I can do that?


Solution

  • Well the ok :: (FilterMonad Response m) => a -> m a function is implemented as [src]:

    ok :: (FilterMonad Response m) => a -> m a
    ok = resp 200
    

    So it is the same way like you would write an ok response, except that you should use resp :: (FilterMonad Response m) => Int -> b -> m b with a custom return code.

    For example:

    resp 405 "Method not allowed"
    

    So we can for example block PUT and POST requests with something like:

    main :: IO ()
    main = simpleHTTP nullConf $ msum
             [ do method GET
                  ok $ "This is allowed.\n"
             , do method PUT
                  (resp 405) $ "Method not allowed"
             , do method POST
                  (resp 405) $ "Method not allowed"
             ]