Last active
February 4, 2022 19:04
-
-
Save reu/9f6cf9aef88780c6544a6b8b425a3ddd to your computer and use it in GitHub Desktop.
HTTP chunked (introdução HTTP dos estagiários)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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