Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
sol committed Sep 8, 2024
1 parent bc65b6b commit 56bfe67
Showing 1 changed file with 22 additions and 20 deletions.
42 changes: 22 additions & 20 deletions src/Client.hs
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,36 @@ module Client (client) where

import Imports

import Network.HTTP.Client
import Network.HTTP.Client.Internal (Response(..))
import Network.Socket
import Network.HTTP.Types
import Network.Socket (connect)
import Network.HTTP.Client
import Network.HTTP.Client.Internal (Connection, Response(..))
import qualified Data.ByteString.Lazy as L

import HTTP (newSocket, socketAddr, socketName)
import HTTP (newSocket, socketName)

client :: FilePath -> IO (Bool, L.ByteString)
client dir = fromRight connectError <$> tryJust p go
client dir = handleConnectionErrors name $ do
manager <- newManager defaultManagerSettings {managerRawConnection = return newConnection}
Response{..} <- httpLbs "http://localhost/" manager
return (statusIsSuccessful responseStatus, responseBody)
where
connectError :: (Bool, L.ByteString)
connectError = (False, "could not connect to " <> fromString (socketName dir) <> "\n")
name :: FilePath
name = socketName dir

newConnection :: Maybe HostAddress -> String -> Int -> IO Connection
newConnection _ _ _ = do
sock <- newSocket
connect sock (SockAddrUnix name)
socketConnection sock 8192

p :: HttpException -> Maybe ()
p e = case e of
HttpExceptionRequest _ (ConnectionFailure se) -> guard (isDoesNotExistException se) >> Just ()
handleConnectionErrors :: String -> IO (Bool, L.ByteString) -> IO (Bool, L.ByteString)
handleConnectionErrors name = fmap (either id id) . tryJust connectionError
where
connectionError :: HttpException -> Maybe (Bool, L.ByteString)
connectionError = \ case
HttpExceptionRequest _ (ConnectionFailure e) | isDoesNotExistException e -> Just (False, "could not connect to " <> fromString name <> "\n")
_ -> Nothing

isDoesNotExistException :: SomeException -> Bool
isDoesNotExistException = maybe False isDoesNotExistError . fromException

go = do
manager <- newManager defaultManagerSettings {managerRawConnection = return newConnection}
Response{..} <- httpLbs "http://localhost/" manager
return (statusIsSuccessful responseStatus, responseBody)

newConnection _ _ _ = do
sock <- newSocket
connect sock $ socketAddr dir
socketConnection sock 8192

0 comments on commit 56bfe67

Please sign in to comment.