Unable to create a custom header to use it in "withManager"

182 Views Asked by At

I can't create a custom header without using OverloadedStrings

import Data.Aeson
import qualified Data.ByteString.Lazy as B
import Network.HTTP.Conduit

import qualified Network.HTTP.Headers as HHeaders
import qualified Network.HTTP.Types as HTypes
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy.Char8 as LC8

-- myHeader1 = (HHeaders.HdrAccept $ C8.pack "some data")
myHeader1 = HHeaders.mkHeader HHeaders.HdrAccept "some data"

get :: String -> IO (Response LC8.ByteString)
get url1 = do
  req1 <- parseUrl url1
  res1 <- withManager $ httpLbs req1 { method = HTypes.methodGet, requestHeaders = [myHeader1] }
  return res1

An error:

Couldn't match type ‘HHeaders.Header’
                   with ‘(HTypes.HeaderName, C8.ByteString)’
    Expected type: HTypes.Header
      Actual type: HHeaders.Header
    In the expression: myHeader1
    In the ‘requestHeaders’ field of a record

What am I doing wrong?

1

There are 1 best solutions below

2
On BEST ANSWER

Network.HTTP.Conduit and Network.HTTP.Headers are from incompatible HTTP libraries. Request headers for http-conduit/http-client can be created using the http-types library:

import Data.Aeson
import qualified Data.ByteString.Lazy as B
import Network.HTTP.Conduit as HHeaders
import qualified Network.HTTP.Types as HTypes
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy.Char8 as LC8

myHeader1 = (HTypes.hAccept, C8.pack "some data")

get :: String -> IO (Response LC8.ByteString)
get url1 = do
  req1 <- parseUrl "some url"
  res1 <- withManager $ httpLbs req1 { method = HTypes.methodGet, requestHeaders = [myHeader1] }
  return res1

To clarify:

You were importing Network.HTTP.Headers from the HTTP library. Although the imports look similar, this is a self-contained library which defines it's own header types and not intended to be used with http-types.

http-client is compatible with the http-types. If you follow the definition for RequestHeader it will lead you to http-types.

In the future, one way to check the compatibility of orthogonal libraries is to look at the build depends on the Hackage index or follow the types as far as possible.