~ubuntu-branches/ubuntu/quantal/haskell-wai-extra/quantal

« back to all changes in this revision

Viewing changes to Network/Wai/Middleware/MethodOverridePost.hs

  • Committer: Package Import Robot
  • Author(s): Clint Adams
  • Date: 2012-05-15 00:58:38 UTC
  • mfrom: (2.1.7 sid)
  • Revision ID: package-import@ubuntu.com-20120515005838-zicbz35rrqbn305y
Tags: 1.2.0.4-1
New upstream version.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
{-# LANGUAGE OverloadedStrings #-}
 
2
-----------------------------------------------------------------
 
3
-- | Module : Network.Wai.Middleware.MethodOverridePost
 
4
--
 
5
-- Changes the request-method via first post-parameter _method.
 
6
-----------------------------------------------------------------
 
7
module Network.Wai.Middleware.MethodOverridePost
 
8
  ( methodOverridePost
 
9
  ) where
 
10
 
 
11
import Network.Wai
 
12
import Network.HTTP.Types           (parseQuery)
 
13
import Data.Monoid                  (mconcat)
 
14
import Data.Conduit.Lazy            (lazyConsume)
 
15
import Control.Monad.Trans.Resource (ResourceT)
 
16
import Data.Conduit.List            (sourceList)
 
17
 
 
18
-- | Allows overriding of the HTTP request method via the _method post string parameter.
 
19
--
 
20
-- * Looks for the Content-Type requestHeader.
 
21
--
 
22
-- * If the header is set to application/x-www-form-urlencoded
 
23
-- and the first POST parameter is _method
 
24
-- then it changes the request-method to the value of that
 
25
-- parameter.
 
26
--
 
27
-- * This middlware only applies when the initial request method is POST.
 
28
--
 
29
methodOverridePost :: Middleware
 
30
methodOverridePost app req = case (requestMethod req, lookup "Content-Type" (requestHeaders req)) of
 
31
  ("POST", Just "application/x-www-form-urlencoded") -> setPost req >>= app
 
32
  _                                                  -> app req
 
33
 
 
34
setPost :: Request -> ResourceT IO Request
 
35
setPost req = do
 
36
  body <- lazyConsume (requestBody req)
 
37
  case parseQuery (mconcat body) of
 
38
    (("_method", Just newmethod):_) -> return $ req {requestBody = sourceList body, requestMethod = newmethod}
 
39
    _                               -> return $ req {requestBody = sourceList body}