我正在尝试发送具有特定数量的字节和块的超级响应。我不知道如何生成通用分块响应或设置传输编码标头。似乎有一个用于 hyper 的 httpWriter/chunkedWriter 现在已被折旧。
这是我的尝试,但是未设置传输编码标头,并且我不认为这是获得分块响应的正确方法。
let chunked_body = "5\r\nhello\r\n5\r\n worl\r\n1\r\nd\r\n0\r\n\r\n";
let mut resp: hyper::Response<Body> = Response::new(Body::from(chunked_body));
resp.headers_mut().insert(TRANSFER_ENCODING, HeaderValue::from_static("Chunked"));
Ok(resp)
Run Code Online (Sandbox Code Playgroud)
分块传输编码是 HTTP/1.1 的一部分,而不是 HTTP/2 的一部分。当处理程序以分块流响应时,Hyper 将根据客户端支持的 HTTP 版本执行“正确的操作”。
例如,以下内容将在 HTTP/1.1 中发送分块响应,但如果客户端支持 HTTP/2,则使用数据帧:
async fn handle(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
let chunked_body = vec!["Hello", ", ", "worl", "d", "!"];
let stream = stream::iter(chunked_body.into_iter().map(Result::<_, Infallible>::Ok));
let body = Body::wrap_stream(stream);
Ok(Response::new(body))
}
Run Code Online (Sandbox Code Playgroud)
此响应的标头(在客户端上强制使用 HTTP/1.1 时)是:
async fn handle(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
let chunked_body = vec!["Hello", ", ", "worl", "d", "!"];
let stream = stream::iter(chunked_body.into_iter().map(Result::<_, Infallible>::Ok));
let body = Body::wrap_stream(stream);
Ok(Response::new(body))
}
Run Code Online (Sandbox Code Playgroud)
如果您希望仅支持 HTTP/1.1,则可以在Server
构建器上使用Builder::http1_only(true)
.