I have a wai middleware that produces two values:
- A request id generated randomly for each request
- A User from a request to another service.
Here is the code:
addRequestIdToRequestHeader' :: Application -> Application
addRequestIdToRequestHeader' app req respond = do
rid <- nextRequestId :: IO ByteString
user <- fetchUserByReq req :: IO User
req' <- attachUserAndRequestIdToRequest user rid
app req' respond
Now I have a route GET /user
. Inside of this route, I’d like to have access to the request id and the User. As an example, I might just print them in the log.
main :: IO ()
main =
scotty 8080 $ do
get "/user" $ do
req <- request
rid <- liftAndCatchIO $ getRequestIdFromRequest req
user <- liftAndCatchIO $ getUserFromRequest req
liftAndCatchIO $ print rid
liftAndCatchIO $ print user
text $ username user
The question is since the request id and the User are generated from the middleware, how to access them from the route? Basically how to implement the following functions used in the above code:
attachUserAndRequestIdToRequest :: User -> ByteString -> Request -> IO Request
getRequestIdFromRequest :: Request -> IO ByteString
getUserFromRequest :: Request -> IO User
The scenario is the middleware is an Auth middleware, which forwards the request to another service for authentication and gets back the user value, which will be needed in the routes.