fix(fs): Return 0 content length for range requests for empty files (#556)

This commit is contained in:
David Herberth 2025-04-09 14:57:25 +02:00 committed by GitHub
parent 33645694bd
commit 6c20928e50
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 26 additions and 1 deletions

0
test-files/empty.txt Normal file
View File

View File

@ -269,12 +269,18 @@ fn build_response(output: FileOpened) -> Response<ResponseBody> {
empty_body()
};
let content_length = if size == 0 {
0
} else {
range.end() - range.start() + 1
};
builder
.header(
header::CONTENT_RANGE,
format!("bytes {}-{}/{}", range.start(), range.end(), size),
)
.header(header::CONTENT_LENGTH, range.end() - range.start() + 1)
.header(header::CONTENT_LENGTH, content_length)
.status(StatusCode::PARTIAL_CONTENT)
.body(body)
.unwrap()

View File

@ -506,6 +506,25 @@ async fn access_space_percent_encoded_uri_path() {
assert_eq!(res.headers()["content-type"], "text/plain");
}
#[tokio::test]
async fn read_partial_empty() {
let svc = ServeDir::new("../test-files");
let req = Request::builder()
.uri("/empty.txt")
.header("Range", "bytes=0-")
.body(Body::empty())
.unwrap();
let res = svc.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::PARTIAL_CONTENT);
assert_eq!(res.headers()["content-length"], "0");
assert_eq!(res.headers()["content-range"], "bytes 0-0/0");
let body = to_bytes(res.into_body()).await.ok().unwrap();
assert!(body.is_empty());
}
#[tokio::test]
async fn read_partial_in_bounds() {
let svc = ServeDir::new("..");