summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Smeding <tom@tomsmeding.com>2026-05-08 21:58:08 +0200
committerTom Smeding <tom@tomsmeding.com>2026-05-08 21:58:08 +0200
commit92a9e5663540e47d1f4563aca4365ecce781205f (patch)
treee99d409c02ea25e3b895a5ee182dec449c98337f
parent1b0c7a30c96685628f7dbe155af987519568588f (diff)
Catch error in sendMany and don't throw
-rw-r--r--mini-http-server/Network/HTTP/Server/Mini/Printer.hs35
1 files changed, 21 insertions, 14 deletions
diff --git a/mini-http-server/Network/HTTP/Server/Mini/Printer.hs b/mini-http-server/Network/HTTP/Server/Mini/Printer.hs
index ab6c1f6..77b88ce 100644
--- a/mini-http-server/Network/HTTP/Server/Mini/Printer.hs
+++ b/mini-http-server/Network/HTTP/Server/Mini/Printer.hs
@@ -9,6 +9,7 @@ import Network.Socket
import Network.Socket.ByteString
import Network.HTTP.Server.Mini.Types
+import System.IO.Error (catchIOError)
sendResponse :: Socket -> Response -> IO ()
@@ -20,20 +21,26 @@ sendResponse conn (Response status hdrs (BodyFile path)) =
sendResponseChunks :: Socket -> Status -> [(Header, ByteString)] -> BSL.ByteString -> IO ()
sendResponseChunks conn (Status code reason) hdrs body =
- sendMany conn $
- BSL.toStrict (BSB.toLazyByteString
- (BSB.shortByteString "HTTP/1.1 "
- <> BSB.intDec code
- <> BSB.char8 ' '
- <> BSB.shortByteString reason
- <> BSB.shortByteString "\r\n"
- <> foldMap (\(key, val) ->
- BSB.shortByteString key <> BSB.shortByteString ": "
- <> BSB.byteString (wrapHdrVal val) <> BSB.shortByteString "\r\n")
- hdrs
- <> BSB.shortByteString "Content-Length: " <> BSB.int64Dec (BSL.length body)
- <> BSB.shortByteString "\r\nConnection: close\r\n\r\n"))
- : BSL.toChunks body
+ catchIOError
+ (sendMany conn $
+ BSL.toStrict (BSB.toLazyByteString
+ (BSB.shortByteString "HTTP/1.1 "
+ <> BSB.intDec code
+ <> BSB.char8 ' '
+ <> BSB.shortByteString reason
+ <> BSB.shortByteString "\r\n"
+ <> foldMap (\(key, val) ->
+ BSB.shortByteString key <> BSB.shortByteString ": "
+ <> BSB.byteString (wrapHdrVal val) <> BSB.shortByteString "\r\n")
+ hdrs
+ <> BSB.shortByteString "Content-Length: " <> BSB.int64Dec (BSL.length body)
+ <> BSB.shortByteString "\r\nConnection: close\r\n\r\n"))
+ : BSL.toChunks body)
+ (\_ ->
+ -- If an IO error occurs during sending, that ought to be sendMany, in
+ -- which case we just exit: if we can't write, we won't be able to write
+ -- in the future, and we might as well give up on this connection.
+ return ())
wrapHdrVal :: ByteString -> ByteString
wrapHdrVal bs = BS.intercalate (BS.singleton 32) (BS.split 10 bs)