on master help sign in
Support setting Accept headers from ‘HttpResponse’ instances

Added the new ‘acceptHeader’ method to the ‘HttpResponse’ type class. Notably, the ‘jsonResponse’ method now sets "Accept" header to "application/json".

commitf598f8c4ff949d8392a1da3ced66a2f6313357c1 authorGeorgi Lyubenov <godzbanebane@gmail.com> dateTue 18 Jun 2019, 22:08 (7 years ago) parent8ad6fe4
2 files changed+25−4
CHANGELOG.md+5−1 Network/HTTP/Req.hs+20−3
CHANGELOG.md+5−1
@@ -1,7 +1,11 @@
1−## Unreleased
1+## Req 2.2.0
22
33* Dropped support for GHC 7.10.
44
5+* Added the new `acceptHeader` method to the `HttpResponse` type class.
6+ Notably, the `jsonResponse` method now sets `"Accept"` header to
7+ `"application/json"`.
8+
59## Req 2.0.1
610
711* Fixed the `httpbin` tests (they changed something on the server again).
Network/HTTP/Req.hs+20−3
@@ -102,7 +102,6 @@
102102{-# LANGUAGE ScopedTypeVariables #-}
103103{-# LANGUAGE TypeFamilies #-}
104104{-# LANGUAGE UndecidableInstances #-}
105−{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
106105
107106module Network.HTTP.Req
108107 ( -- * Making a request
@@ -391,8 +390,13 @@ req
391390 -> Proxy response -- ^ A hint how to interpret response
392391 -> Option scheme -- ^ Collection of optional parameters
393392 -> m response -- ^ Response
394−req method url body Proxy options =
395− reqBr method url body options getHttpResponse
393+req method url body responseProxy options =
394+ reqBr method url body (options <> extraOptions) getHttpResponse
395+ where
396+ extraOptions =
397+ case acceptHeader responseProxy of
398+ Nothing -> mempty
399+ Just accept -> header "Accept" accept
396400
397401-- | A version of 'req' that does not use one of the predefined instances of
398402-- 'HttpResponse' but instead allows the user to consume @'L.Response'
@@ -1440,6 +1444,7 @@ instance FromJSON a => HttpResponse (JsonResponse a) where
14401444 case A.eitherDecode (BL.fromChunks chunks) of
14411445 Left e -> throwIO (JsonHttpException e)
14421446 Right x -> return $ JsonResponse (x <$ r)
1447+ acceptHeader Proxy = Just "application/json"
14431448
14441449-- | Use this as the fourth argument of 'req' to specify that you want it to
14451450-- return the 'JsonResponse' interpretation.
@@ -1637,6 +1642,18 @@ class HttpResponse response where
16371642 -> IO response
16381643 -- ^ The final result
16391644
1645+ -- | The value of @\"Accept\"@ header. This is useful, for example, if a
1646+ -- website supports both @XML@ and @JSON@ responses, and decides what to
1647+ -- reply with based on what @Accept@ headers you have sent.
1648+ --
1649+ -- __Note__: manually specified 'Options' that set the @\"Accept\"@ header
1650+ -- will take precedence.
1651+ --
1652+ -- @since 2.2.0
1653+
1654+ acceptHeader :: Proxy response -> Maybe ByteString
1655+ acceptHeader Proxy = Nothing
1656+
16401657----------------------------------------------------------------------------
16411658-- Other
16421659