adius
adius

Reputation: 14992

How to limit file size for multipart/form-data upload to Servant server?

The documentation at hackage.haskell.org/package/servant-multipart says about the main combinator type MultipartForm tag a following:

Note that the behavior of this combinator is configurable, by using serveWith from servant-server instead of serve, which takes an additional Context argument. It simply is an heterogeneous list where you can for example store a value of type MultipartOptions that has the configuration that you want, which would then get picked up by servant-multipart.

And later:

data MultipartOptions tag
Global options for configuring how the server should handle multipart data.
generalOptions lets you specify mostly multipart parsing related options, such as the maximum file size …

However, I don't understand how to correctly call the mentioned serveWithContext:

serveWithContext 
  :: (HasServer api context, ServerContext context) 
  => Proxy api 
  -> Context context 
  -> Server api  
  -> Application

Searching for its usage on GitHub also didn't enlighten me, unfortunately.

Upvotes: 4

Views: 1000

Answers (1)

adius
adius

Reputation: 14992

Following code does the job:

import Prelude (($))
import Servant
  ( Application, Proxy(Proxy)
  , Context(EmptyContext, (:.)), serveWithContext
  )
import Servant.Multipart
  ( MultipartOptions(generalOptions)
  , defaultMultipartOptions, Mem
  )
import Network.Wai.Parse
  ( defaultParseRequestBodyOptions, setMaxRequestFileSize )

app :: Application
app =
  let
    size10MB = 10000000
    multipartOpts = (defaultMultipartOptions (Proxy :: Proxy Mem))
      { generalOptions =
          setMaxRequestFileSize size10MB
          defaultParseRequestBodyOptions
      }
    context = multipartOpts :. EmptyContext
  in
    serveWithContext appApi context appSserver

Make sure to use the correct MultipartData tag for the Proxy type (Mem or Tmp). Documentation: hackage.haskell.org/package/servant-multipart

You can check out hackage.haskell.org/package/wai-extra for all available config changes.

Upvotes: 4

Related Questions