module Network.Wai.Middleware.MethodOverridePost
( methodOverridePost
) where
import Network.Wai
import Network.HTTP.Types (parseQuery)
import Data.Monoid (mconcat)
import Data.Conduit.Lazy (lazyConsume)
import Control.Monad.Trans.Resource (ResourceT)
import Data.Conduit.List (sourceList)
methodOverridePost :: Middleware
methodOverridePost app req = case (requestMethod req, lookup "Content-Type" (requestHeaders req)) of
("POST", Just "application/x-www-form-urlencoded") -> setPost req >>= app
_ -> app req
setPost :: Request -> ResourceT IO Request
setPost req = do
body <- lazyConsume (requestBody req)
case parseQuery (mconcat body) of
(("_method", Just newmethod):_) -> return $ req {requestBody = sourceList body, requestMethod = newmethod}
_ -> return $ req {requestBody = sourceList body}