Create a gist now

Instantly share code, notes, and snippets.

Servant CSV download sample
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
import Control.Monad.IO.Class -- liftIO
import Control.Monad.Trans.Except -- Handler
import Data.Aeson.Types -- JSON
import Data.Aeson.Parser -- JSON
import GHC.Generics
import Network.Wai.Handler.Warp
import Servant
import qualified Network.HTTP.Media as M
import Text.CSV
import qualified Data.ByteString.Lazy.Char8 as C
type MyAPI = "csv" :> Capture "file" String :> Get '[CSV'] CSV
data CSV'
instance Accept CSV' where
contentType _ = "application" M.// "csv"
instance MimeRender CSV' CSV where
mimeRender _ val = C.pack $ printCSV val
csv' :: String -> Handler CSV
csv' f = do
ret <- liftIO $ parseCSVFromFile ("./data/" ++ f ++ ".csv")
case ret of
Left l -> throwError err400 {errBody="parse error"}
Right r -> return r
myServer :: Server MyAPI
myServer = csv'
myProxy :: Proxy MyAPI
myProxy = Proxy
myApp :: Application
myApp = serve myProxy myServer
main :: IO ()
main = run 8081 myApp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment