|
| 1 | +{-# LANGUAGE DataKinds #-} |
| 2 | +{-# LANGUAGE TypeOperators #-} |
| 3 | +{-# LANGUAGE OverloadedStrings #-} |
| 4 | +{-# LANGUAGE TypeFamilies #-} |
| 5 | + |
| 6 | +import Control.Monad |
| 7 | +import Control.Monad.IO.Class |
| 8 | +import Network.Socket (withSocketsDo) |
| 9 | +import Network.Wai.Handler.Warp |
| 10 | +import Servant |
| 11 | +import Servant.Multipart |
| 12 | + |
| 13 | +import qualified Data.ByteString.Lazy as LBS |
| 14 | + |
| 15 | +-- Our API, which consists in a single POST endpoint at / |
| 16 | +-- that takes a multipart/form-data request body and |
| 17 | +-- pretty-prints the data it got to stdout before returning 0. |
| 18 | +type API = MultipartForm Mem (MultipartData Mem) :> Post '[JSON] Integer |
| 19 | + |
| 20 | +api :: Proxy API |
| 21 | +api = Proxy |
| 22 | + |
| 23 | +-- The handler for our single endpoint. |
| 24 | +-- Its concrete type is: |
| 25 | +-- MultipartData -> Handler Integer |
| 26 | +-- |
| 27 | +-- MultipartData consists in textual inputs, |
| 28 | +-- accessible through its "inputs" field, as well |
| 29 | +-- as files, accessible through its "files" field. |
| 30 | +upload :: Server API |
| 31 | +upload multipartData = liftIO $ do |
| 32 | + putStrLn "Inputs:" |
| 33 | + forM_ (inputs multipartData) $ \input -> |
| 34 | + putStrLn $ " " ++ show (iName input) |
| 35 | + ++ " -> " ++ show (iValue input) |
| 36 | + |
| 37 | + forM_ (files multipartData) $ \file -> do |
| 38 | + let content = fdPayload file |
| 39 | + putStrLn $ "Content of " ++ show (fdFileName file) |
| 40 | + LBS.putStr content |
| 41 | + return 0 |
| 42 | + |
| 43 | +startServer :: IO () |
| 44 | +startServer = run 8080 $ serve api upload |
| 45 | + |
| 46 | +main :: IO () |
| 47 | +main = withSocketsDo startServer |
0 commit comments