Skip to content

Allow HEAD requests to files paths #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions adafruit_httpserver/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ def send_file(
filename: str = "index.html",
root_path: str = "./",
buffer_size: int = 1024,
head_only: bool = False,
) -> None:
"""
Send response with content of ``filename`` located in ``root_path``.
Expand All @@ -197,9 +198,10 @@ def send_file(
content_length=file_length,
)

with open(root_path + filename, "rb") as file:
while bytes_read := file.read(buffer_size):
self._send_bytes(self.request.connection, bytes_read)
if not head_only:
with open(root_path + filename, "rb") as file:
while bytes_read := file.read(buffer_size):
self._send_bytes(self.request.connection, bytes_read)
self._response_already_sent = True

def send_chunk(self, chunk: str = "") -> None:
Expand Down
6 changes: 5 additions & 1 deletion adafruit_httpserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,12 +167,16 @@ def poll(self):
handler(request)

# If no handler exists and request method is GET, try to serve a file.
elif handler is None and request.method == HTTPMethod.GET:
elif handler is None and request.method in (
HTTPMethod.GET,
HTTPMethod.HEAD,
):
filename = "index.html" if request.path == "/" else request.path
HTTPResponse(request).send_file(
filename=filename,
root_path=self.root_path,
buffer_size=self.request_buffer_size,
head_only=(request.method == HTTPMethod.HEAD),
)
else:
HTTPResponse(
Expand Down