HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Modulewai-conduit-3.0.0.4Haskell2010

Network.Wai.Conduit

A light-weight wrapper around Network.Wai to provide easy conduit support.

  • 8 types
  • 40 values

Request body

1 declaration

Response body

2 declarations

Re-export

45 declarations
datadata Request
#

Information on the request sent by the client. This abstracts away the details of the underlying implementation.

Instances1Show
  • Show RequestDefined in wai-3.2.4 · Network.Wai.Internal
valuevault :: Request -> Vault
#

A location for arbitrary data to be shared by applications and middleware.

Deprecated. requestBody's name is misleading because it only gets a partial chunk of the body. Use getRequestBodyChunk instead when getting the field, and setRequestBodyChunks when setting the field.

Get the next chunk of the body. Returns empty when the body is fully consumed. Since 3.2.2, this is deprecated in favor of getRequestBodyChunk.

valueisSecure :: Request -> Bool
#

Was this request made over an SSL connection?

Note that this value will not tell you if the client originally made this request over SSL, but rather whether the current connection is SSL. The distinction lies with reverse proxies. In many cases, the client will connect to a load balancer over SSL, but connect to the WAI handler without SSL. In such a case, isSecure will be False, but from a user perspective, there is a secure connection.

valuepathInfo :: Request -> [Text]
#

Path info in individual pieces - the URL without a hostname/port and without a query string, split on forward slashes.

Extra path information sent by the client. The meaning varies slightly depending on backend; in a standalone server setting, this is most likely all information after the domain name. In a CGI application, this would be the information following the path to the CGI executable itself.

Middlewares and routing tools should not modify this raw value, as it may be used for such things as creating redirect destinations by applications. Instead, if you are writing a middleware or routing framework, modify the pathInfo instead. This is the approach taken by systems like Yesod subsites.

Note: At the time of writing this documentation, there is at least one system (Network.Wai.UrlMap from wai-extra) that does not follow the above recommendation. Therefore, it is recommended that you test the behavior of your application when using rawPathInfo and any form of library that might modify the Request.

If no query string was specified, this should be empty. This value will include the leading question mark. Do not modify this raw value - modify queryString instead.

Creating Response from a stream of values.

In order to allocate resources in an exception-safe manner, you can use the bracket pattern outside of the call to responseStream. As a trivial example:

app :: Application
app req respond = bracket_
    (putStrLn "Allocating scarce resource")
    (putStrLn "Cleaning up")
    $ respond $ responseStream status200 [] $ \write flush -> do
        write $ byteString "Hello\n"
        flush
        write $ byteString "World\n"

Note that in some cases you can use bracket from inside responseStream as well. However, placing the call on the outside allows your status value and response headers to depend on the scarce resource.

valueresponseRaw
  1. :: IO ByteString -> (ByteString -> IO ()) -> IO ()
  2. -> Response
  3. -> Response
#

Create a response for a raw application. This is useful for "upgrade" situations such as WebSockets, where an application requests for the server to grant it raw network access.

This function requires a backup response to be provided, for the case where the handler in question does not support such upgrading (e.g., CGI apps).

In the event that you read from the request body before returning a responseRaw, behavior is undefined.

datadata ResponseReceived
#

A special datatype to indicate that the WAI handler has received the response. This is to avoid the need for Rank2Types in the definition of Application.

It is highly advised that only WAI handlers import and use the data constructor for this data type.

typetype StreamingBody = (Builder -> IO ()) -> IO () -> IO ()
#

Represents a streaming HTTP response body. It's a function of two parameters; the first parameter provides a means of sending another chunk of data, and the second parameter provides a means of flushing the data to the client.

Get the request body as a lazy ByteString. This uses lazy I/O under the surface, and therefore all typical warnings regarding lazy I/O apply.

Note: Since this function consumes the request body, future calls to it will return the empty string.

Creating Response from Builder.

Some questions and answers about the usage of Builder here:

Q1. Shouldn't it be at the user's discretion to use Builders internally and then create a stream of ByteStrings?

A1. That would be less efficient, as we wouldn't get cheap concatenation with the response headers.

Q2. Isn't it really inefficient to convert from ByteString to Builder, and then right back to ByteString?

A2. No. If the ByteStrings are small, then they will be copied into a larger buffer, which should be a performance gain overall (less system calls). If they are already large, then an insert operation is used to avoid copying.

Q3. Doesn't this prevent us from creating comet-style servers, since data will be cached?

A3. You can force a Builder to output a ByteString before it is an optimal size by sending a flush command.

Get the request body as a lazy ByteString. However, do not use any lazy I/O, instead reading the entire body into memory strictly.

Note: Since this function consumes the request body, future calls to it will return the empty string.

The WAI application.

Note that, since WAI 3.0, this type is structured in continuation passing style to allow for proper safe resource handling. This was handled in the past via other means (e.g., ResourceT). As a demonstration:

app :: Application
app req respond = bracket_
    (putStrLn "Allocating scarce resource")
    (putStrLn "Cleaning up")
    (respond $ responseLBS status200 [] "Hello World")

A Middleware is a component that sits between the server and application.

It can modify both the Request and Response, to provide simple transformations that are required for all (or most of) your web server’s routes.

Users of middleware

If you are trying to apply one or more Middlewares to your Application, just call them as functions.

For example, if you have corsMiddleware and authorizationMiddleware, and you want to authorize first, you can do:

let allMiddleware app = authorizationMiddleware (corsMiddleware app)

to get a new Middleware, which first authorizes, then sets, CORS headers. The “outer” middleware is called first.

You can also chain them via (.):

let allMiddleware =
        authorizationMiddleware
      . corsMiddleware
      . … more middleware here …

Then, once you have an app :: Application, you can wrap it in your middleware:

let myApp = allMiddleware app :: Application

and run it as usual:

Warp.run port myApp

Authors of middleware

When fully expanded, Middleware has the type signature:

(Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived) -> Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived

or if we shorten to type Respond = Response -> IO ResponseReceived:

(Request -> Respond -> IO ResponseReceived) -> Request -> Respond -> IO ResponseReceived

so a middleware definition takes 3 arguments, an inner application, a request and a response callback.

Compare with the type of a simple Application:

Request -> Respond -> IO ResponseReceived

It takes the Request and Respond, but not the extra application.

Said differently, a middleware has the power of a normal Application — it can inspect the Request and return a Response — but it can (and in many cases it should) also call the Application which was passed to it.

Modifying the Request

A lot of middleware just looks at the request and does something based on its values.

For example, the authorizationMiddleware from above could look at the Authorization HTTP header and run JWT verification logic against the database.

authorizationMiddleware app req respond = do
  case verifyJWT (requestHeaders req) of
    InvalidJWT err -> respond (invalidJWTResponse err)
    ValidJWT -> app req respond

Notice how the inner app is called when the validation was successful. If it was not, we can respond e.g. with HTTP 401 Unauthorized, by constructing a Response with responseLBS and passing it to respond.

Passing arguments to and from your Middleware

Middleware must often be configurable. Let’s say you have a type JWTSettings that you want to be passed to the middleware. Simply pass an extra argument to your middleware. Then your middleware type turns into:

authorizationMiddleware :: JWTSettings -> Application -> Request -> Respond -> IO ResponseReceived
authorizationMiddleware jwtSettings req respond =
  case verifyJWT jwtSettings (requestHeaders req) of
    InvalidJWT err -> respond (invalidJWTResponse err)
    ValidJWT -> app req respond

or alternatively:

authorizationMiddleware :: JWTSettings -> Middleware

Perhaps less intuitively, you can also pass on data from middleware to the wrapped Application:

authorizationMiddleware :: JWTSettings -> (JWT -> Application) -> Request -> Respond -> IO ResponseReceived
authorizationMiddleware jwtSettings req respond =
  case verifyJWT jwtSettings (requestHeaders req) of
    InvalidJWT err -> respond (invalidJWTResponse err)
    ValidJWT jwt -> app jwt req respond

although then, chaining different middleware has to take this extra argument into account:

let finalApp =
      authorizationMiddleware
        (\jwt -> corsMiddleware
           (… more middleware here …
             (app jwt)))

Modifying the Response

Middleware can also modify the Response that is returned by the inner application.

This is done by taking the respond callback, using it to define a new respond', and passing this new respond' to the app:

gzipMiddleware app req respond = do
  let respond' resp = do
        resp' <- gzipResponseBody resp
        respond resp'
  app req respond'

However, modifying the response (especially the response body) is not trivial, so in order to get a sense of how to do it (dealing with the type of responseToStream), it’s best to look at an example, for example the GZIP middleware of wai-extra.