Hey everyone,
I’m playing around with Network.HTTP.Req as an http/https client library to make some requests to a local REST API. I can’t seem to wrap my head around the typing/implementation of the Scheme/Url types. I would just like to be able to let the end user choose between http and https at runtime without duplicating much code. Here’s a concrete example:
r <-
if secure then
req
GET (https host /: "rest" /: "db" /: "status")
NoReqBody
jsonResponse
$ port port'
<> header "X-API-Key" apiKey
<> "folder" =: folder
else
req
GET (http host /: "rest" /: "db" /: "status")
NoReqBody
jsonResponse
$ port port'
<> header "X-API-Key" apiKey
<> "folder" =: folder
What I would like to do is determine if the secure bool value is set in advance and only have the rest of the request code typed out once, i.e. something like this:
let scheme' = if secure then https else http
r <-
req
GET (scheme' host /: "rest" /: "db" /: "status")
NoReqBody
jsonResponse
$ port port'
<> header "X-API-Key" apiKey
<> "folder" =: folder
Due to my unfamiliarity with the strange typing of the Url/Scheme types I can’t figure out how to make that happen. I get these errors:
• Couldn't match type ‘'Http’ with ‘'Https’
Expected: Text -> Url 'Https
Actual: Text -> Url 'Http
• In the expression: http
In the expression: if secure then https else http
In an equation for ‘scheme'’: scheme' = if secure then https else http [-Wdeferred-type-errors]
Url: https://hackage.haskell.org/package/req-3.13.2/docs/src/Network.HTTP.Req.html#Url
Scheme: https://hackage.haskell.org/package/req-3.13.2/docs/src/Network.HTTP.Req.html#Scheme
data Url (scheme :: Scheme) = Url Scheme (NonEmpty Text)
-- NOTE The second value is the path segments in reversed order.
deriving (Eq, Ord, Show, Data, Typeable, Generic)
type role Url nominal
instance (Typeable scheme) => TH.Lift (Url scheme) where
...
data Scheme
= -- | HTTP
Http
| -- | HTTPS
Https
deriving (Eq, Ord, Show, Data, Typeable, Generic, TH.Lift)
It seems like it has to do with the TH/Lift’ing implementation, but I can’t understand it. Can anyone enlighten me on what’s happening and/or a decent solution for what I’m trying to do?