-,
{-
{-
{-
{-
{-
{-
{-
{-
{-
, , . , , , HTTP. ReqBody, , , , , .
ReqBody :
module Body where
import Control.Monad.Trans (liftIO)
import Data.Proxy (Proxy(..))
import Network.Wai (lazyRequestBody)
import Data.Aeson
import Servant.API
import Servant.Server
import Servant.Server.Internal
data Body a
instance (FromJSON a, HasServer api context) => HasServer (Body a :> api) context where
type ServerT (Body a :> api) m = a -> ServerT api m
route Proxy context subserver =
route (Proxy :: Proxy api) context (addBodyCheck subserver (withRequest bodyCheck))
where
bodyCheck request = do
body <- liftIO (lazyRequestBody request)
case eitherDecode body of
Left (BodyError -> e) ->
delayedFailFatal err400 { errBody = encode e }
Right v ->
return v
:
servant-server , , serve (Proxy :: Proxy (Body foo :> bar)) server.
v0.8.1 ReqBody.
, .
a Body. blob JSON HTTP 400.
.
JSON blob:
newtype BodyError = BodyError String
instance ToJSON BodyError where
toJSON (BodyError b) = object ["error" .= b]
servant-server . , , master, arity addBodyCheck .
, "" - , , , , .
:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module Main where
import Data.Proxy (Proxy(..))
import Network.Wai.Handler.Warp (run)
import Servant.API
import Servant.Server
import Body
type API = Body [Int] :> Post '[JSON] [Int]
server :: Server API
server = pure
main :: IO ()
main = do
putStrLn "running on port 8000"
run 8000 (serve (Proxy :: Proxy API) server)
:
~ ❯❯❯ curl -i -XPOST 'http://localhost:8000/'
HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Date: Fri, 20 Jan 2017 01:18:57 GMT
Server: Warp/3.2.9
{"error":"Error in $: not enough input"}%
~ ❯❯❯ curl -id 'hey' -XPOST 'http://localhost:8000/'
HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Date: Fri, 20 Jan 2017 01:19:02 GMT
Server: Warp/3.2.9
{"error":"Error in $: Failed reading: not a valid json value"}%
~ ❯❯❯ curl -id '[1,2,3]' -XPOST 'http://localhost:8000/'
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Date: Fri, 20 Jan 2017 01:19:07 GMT
Server: Warp/3.2.9
Content-Type: application/json
[1,2,3]%
-!
LTS-7.16.
(1) - .
(2) Servant , , API. ReqBody ; , , (GET, POST,...) . , - ReqBody, .
(3) GHC, , . API , typeclass, , -.