Skip to content

Commit 471b0d6

Browse files
committed
add bodies to 404 and 500 responses
This matches the old, more user-friendly behavior. I've also removed irrelevant cache control headers from 404 responses. Signed-off-by: Joel Dice <[email protected]>
1 parent 67e4681 commit 471b0d6

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

src/lib.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use http::{
44
header::{ACCEPT_ENCODING, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_TYPE, ETAG, IF_NONE_MATCH},
55
HeaderName, StatusCode,
66
};
7-
use spin_sdk::http::{Fields, IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam};
7+
use spin_sdk::http::{Fields, IncomingRequest, OutgoingResponse, ResponseOutparam};
88
use std::{
99
fs::File,
1010
io::{Cursor, Read},
@@ -128,9 +128,11 @@ async fn handle_request(req: IncomingRequest, res_out: ResponseOutparam) {
128128
Err(e) => {
129129
eprintln!("Error building response: {e}");
130130
let res = OutgoingResponse::new(500, &Fields::new(&[]));
131-
let body = res.write().expect("response should be writable");
131+
let mut body = res.take_body();
132132
res_out.set(res);
133-
OutgoingBody::finish(body, None);
133+
if let Err(e) = body.send(b"Internal Server Error".to_vec()).await {
134+
eprintln!("Error sending body: {e}");
135+
}
134136
}
135137
}
136138
}
@@ -296,7 +298,7 @@ impl FileServer {
296298
let reader = Self::resolve_and_read(path, enc).transpose()?;
297299
let etag = Self::make_etag(reader)?;
298300
let mut reader = Self::resolve_and_read(path, enc).transpose()?;
299-
let headers = Self::make_headers(path, enc, &etag);
301+
let mut headers = Self::make_headers(path, enc, &etag);
300302

301303
let status = if reader.is_some() {
302304
if etag.as_bytes() == if_none_match {
@@ -306,6 +308,8 @@ impl FileServer {
306308
StatusCode::OK
307309
}
308310
} else {
311+
reader = Some(Box::new(Cursor::new(b"Not Found")));
312+
headers = Vec::new();
309313
StatusCode::NOT_FOUND
310314
};
311315

@@ -415,7 +419,9 @@ mod tests {
415419
let (status, _, reader) =
416420
FileServer::make_response(b"non-exisitent-file", ContentEncoding::None, b"").unwrap();
417421
assert_eq!(status, StatusCode::NOT_FOUND);
418-
assert!(reader.is_none());
422+
let mut actual_body = Vec::new();
423+
reader.unwrap().read_to_end(&mut actual_body).unwrap();
424+
assert_eq!(actual_body.as_slice(), b"Not Found");
419425
}
420426

421427
#[test]
@@ -455,7 +461,9 @@ mod tests {
455461
let (status, _, reader) =
456462
FileServer::make_response(b"non-exisitent-file", ContentEncoding::None, b"").unwrap();
457463
assert_eq!(status, StatusCode::NOT_FOUND);
458-
assert!(reader.is_none());
464+
let mut actual_body = Vec::new();
465+
reader.unwrap().read_to_end(&mut actual_body).unwrap();
466+
assert_eq!(actual_body.as_slice(), b"Not Found");
459467
}
460468

461469
#[test]

0 commit comments

Comments
 (0)