Skip to content

Instantly share code, notes, and snippets.

@radu-matei
Last active October 24, 2023 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radu-matei/6757d8aeb7d3dd41d74bb6367d7a9e8f to your computer and use it in GitHub Desktop.
Save radu-matei/6757d8aeb7d3dd41d74bb6367d7a9e8f to your computer and use it in GitHub Desktop.
use std::{fs::File, io::Read};
use anyhow::Result;
use futures::SinkExt;
use spin_sdk::{
http::{Fields, IncomingRequest, OutgoingResponse, ResponseOutparam},
http_component,
};
const CHUNK_SIZE: usize = 1 * 1024 * 1024; // 1 MB
#[http_component]
async fn handler(req: IncomingRequest, res: ResponseOutparam) {
stream_file(req, res).await.unwrap();
}
async fn stream_file(_req: IncomingRequest, res: ResponseOutparam) -> Result<()> {
let response = OutgoingResponse::new(
200,
&Fields::new(&[(
"content-type".to_string(),
b"application/octet-stream".to_vec(),
)]),
);
let mut body = response.take_body();
ResponseOutparam::set(res, Ok(response));
let mut file =
File::open("target/wasm32-wasi/release/wasi_http_rust_streaming_outgoing_body.wasm")?;
let mut buffer = vec![0; CHUNK_SIZE];
// Read the file in chunks.
loop {
let bytes_read = file.read(&mut buffer[..])?;
if bytes_read == 0 {
break;
}
let data = &buffer[..bytes_read];
body.send(data.to_vec()).await?;
println!("sent {} bytes", data.len());
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment