Skip to content

Instantly share code, notes, and snippets.

@reu
Last active February 4, 2022 19:04
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 reu/9f6cf9aef88780c6544a6b8b425a3ddd to your computer and use it in GitHub Desktop.
Save reu/9f6cf9aef88780c6544a6b8b425a3ddd to your computer and use it in GitHub Desktop.
HTTP chunked (introdução HTTP dos estagiários)
use std::io::Write;
use std::net::TcpListener;
use std::thread::sleep;
use std::time::Duration;
fn main() -> std::io::Result<()> {
let port = std::env::var("PORT").unwrap_or("3000".into());
let listener = TcpListener::bind(format!("0.0.0.0:{port}"))?;
loop {
let (mut stream, _addr) = listener.accept()?;
let headers = [
("Transfer-Encoding", "chunked"),
("Content-Type", "text/csv"),
];
let headers = headers
.map(|(name, val)| format!("{name}: {val}"))
.join("\r\n");
let response = format!("HTTP/1.1 200\r\n{headers}\r\n\r\n");
stream.write_all(response.as_bytes())?;
for i in 0..=100 {
// Cabeçalho da primeira linha
let chunk_content = if i == 0 {
format!("id;nome\n")
} else {
format!("{i};Nome da linha {i}\n")
};
// Formato de cada chunk: tamanho do chunk (em hexa) \r\n conteúdo do chunk \r\n
let chunk = format!(
"{:x}\r\n{}\r\n",
chunk_content.as_bytes().len(),
chunk_content
);
stream.write_all(chunk.as_bytes())?;
if i % 10 == 0 {
// Simulando um delay para gerar as próximas 10 linhas
println!("Gerando próximo chunk...");
sleep(Duration::from_secs(1));
}
}
let last_chunk = "0\r\n\r\n";
stream.write_all(last_chunk.as_bytes())?;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment