发送响应
2025年7月17日小于 1 分钟hyperlanewebrustusage-introductionsend
提示
hyperlane
框架提供了多种响应发送方法,支持完整 HTTP 响应发送、仅响应体发送,以及连接管理。
发送完整 HTTP 响应
send 方法
提示
发送完整的 HTTP 响应,发送后 TCP 连接保留。
let send_result: ResponseResult = ctx.send().await;
send_once 方法
提示
发送完整的 HTTP 响应,发送后立即关闭 TCP 连接。
let send_result: ResponseResult = ctx.send_once().await;
发送响应体
send_body 方法
提示
仅发送响应体内容,发送后 TCP 连接保留。适用于流式响应和 WebSocket。
let send_result: ResponseResult = ctx.send_body().await;
send_once_body 方法
提示
仅发送响应体内容,发送后立即关闭 TCP 连接。
let send_result: ResponseResult = ctx.send_once_body().await;
刷新缓冲区
flush 方法
提示
强制刷新网络缓冲区,确保数据立即发送。
let flush_result: ResponseResult = ctx.flush().await;
基本使用示例
使用框架常量
ctx.set_response_header(CONTENT_TYPE, APPLICATION_JSON).await
.set_response_body(r#"{"status": "ok"}"#).await
.send().await;
流式发送
ctx.set_response_header(CONTENT_TYPE, TEXT_PLAIN).await;
for i in 1..=3 {
let _ = ctx.set_response_body(format!("chunk {}\n", i)).await.send_body().await;
ctx.flush().await;
}
WebSocket 发送
ctx.upgrade_to_ws().await;
let _ = ctx.set_response_body("websocket message").await.send_body().await;