Hello,
I’d like to ask how to modify the request headers in a Servant client.
It seems possible to do this using managerModifyRequest in the http-client package by customizing ManagerSettings, but I was wondering if there’s a built-in or recommended way to achieve this directly within Servant’s client side.
I came across something called ClientMiddleware, which looks like it might be relevant, but I’m not sure how to use it properly.
Any guidance or examples would be greatly appreciated.
Thanks in advance!
Ah, the specific change I want to make is to check and modify the Accept-Encoding header.
Assuming you want to add the same header to every endpoint, I think all you need to do is alter makeClientRequest with something that uses the http-client API to add the header. Something like this (untested):
import Network.HTTP.Client (Request(..))
import Servant.Client
addHdr :: Request -> Request
addHdr req = req
{ requestHeaders = ("Accept-Encoding", "gzip") : requestHeaders req
}
main :: IO ()
main = do
...
let env = mkClientEnv mgr base
let env' = env { makeClientRequest = \base -> fmap addHdr . makeClientRequest env base }
result <- runClientM myAPICalls env'
...
(If you want to specify the header value differently for different endpoints, or for different calls to the same endpoint, you use the Header type in the API like any other endpoint parameter.)
3 Likes