Using http-conduit
I want to download a HTTP URL implementing the following semantics (resulting in IO (Maybe LB.ByteString)
):
- If the HTTP response code is 2xx, return
Just
the response body - If the HTTP response code is 404, return
Nothing
- If the response code indicates a redirect, follow according to standard http-conduit settings
- For any other response code, throw a
StatusCodeException
.
How can I do that using httpLbs
without any libraries beyond http-conduit
and its dependencies?
Note: This question was answered in Q&A form and therefore intentionally does not show research effort.
This is possible by using a custom
checkStatus
similar to one of the offical examples.We will declare
checkStatus200
which passes if the response status code is either 2xx or 404. If it doesn't pass, it calls the defaultcheckStatus
function to throw the appropriate exception.After calling
httpLbs
with aRequest
usingcheckStatus200
, we can check the status code and return eitherJust
the response code orNothing
.