Binary file handling

This commit is contained in:
Matt Arnold 2025-09-09 18:59:38 -04:00
parent 3ed9fc8e92
commit 72bb49c672
3 changed files with 23 additions and 3 deletions

View File

@ -124,7 +124,21 @@ class HttpResponse(AccessDict):
return self.body.write(bytes(stuff, "utf-8"))
return self.body.write(stuff)
# Foreshadowing (n): A literary device in which an author ...
def binary_io(self):
if not self.binmode:
str(self)
hbuf = StringIO()
bbuf = BytesIO()
hbuf.write(f"HTTP/1.1 {self.status}" + CRLF)
length = len(self["body"].getvalue())
for k, v in self["headers"].items():
hbuf.write(f"{k}: {v}\r\n")
if "Content-Length" not in self["headers"]:
hbuf.write(f"Content-Length: {length}\r\n")
hbuf.write(CRLF) # Per RFC 9112
bbuf.write(self.body.getvalue())
return (hbuf.getvalue(), bbuf.getvalue())
def __str__(self):
buf = StringIO()
buf.write(f"HTTP/1.1 {self.status}" + CRLF)
@ -440,8 +454,13 @@ def client_handler(sock):
continue
# gevent.sleep(0.25) # this is a somewhat magical value, see Part II
default = str(server_response) + CRLF
sock.send(default.encode("utf-8"))
if server_response.binmode:
headers, body = server_response.binary_io()
sock.send(headers.encode("utf-8"))
sock.send(body)
else:
default = str(server_response) + CRLF
sock.send(default.encode("utf-8"))
# sock.shutdown(socket.SHUT_RDWR) # we do a more graceful exit here by
# shutting down the socket, makes things faster for TLS
# may have an effect on client response time to but i didn't notice it.

View File

@ -9,6 +9,7 @@
<main>
<h1>Page title</h1>
<img src="rick.jpg"> No Strangers </img>
<p>Hello! this is an example page using <a href="https://github.com/Xe/Xess">Xess</a></p>
<blockquote>When in doubt, create another framework</blockquote>

BIN
htdocs/rick.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB