发送响应
2025年9月27日大约 2 分钟hyperlanewebrustusage-introductionsend
提示
hyperlane
框架提供了多种响应发送方法,支持完整 HTTP 响应发送、仅响应体发送,以及连接管理。
send_with_data
: 发送完整响应并设置响应体。send_once_with_data
: 发送完整响应并立即关闭连接。send_body_with_data
: 仅发送响应体并保留连接。send_body_once_with_data
: 仅发送响应体并立即关闭连接。send_body_list_with_data
: 批量发送响应体,适用于 WebSocket 等场景。send_body_list_once_with_data
: 批量发送响应体并立即关闭连接。
发送完整 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;
发送带数据的响应
send_with_data 方法
提示
发送完整的 HTTP 响应,并将提供的数据作为响应体,发送后 TCP 连接保留。
let send_result: ResponseResult = ctx.send_with_data("Hello, World!").await;
send_once_with_data 方法
提示
发送完整的 HTTP 响应,并将提供的数据作为响应体,发送后立即关闭 TCP 连接。
let send_result: ResponseResult = ctx.send_once_with_data("Hello, World!").await;
send_body_with_data 方法
提示
仅发送响应体内容,并将提供的数据作为响应体,发送后 TCP 连接保留。
let send_result: ResponseResult = ctx.send_body_with_data("chunk data").await;
send_body_once_with_data 方法
提示
仅发送响应体内容,并将提供的数据作为响应体,发送后立即关闭 TCP 连接。
let send_result: ResponseResult = ctx.send_body_once_with_data("final chunk").await;
send_body_list_with_data 方法
提示
批量发送多个响应体数据,适用于 WebSocket 桢列表等场景,发送后 TCP 连接保留。
let frame_list: Vec<ResponseBody> = WebSocketFrame::create_frame_list(&request_body);
ctx.send_body_list_with_data(&frame_list).await.unwrap();
send_body_list_once_with_data 方法
提示
批量发送多个响应体数据,发送后立即关闭 TCP 连接。
let frame_list: Vec<ResponseBody> = WebSocketFrame::create_frame_list(&request_body);
ctx.send_body_list_once_with_data(&frame_list).await.unwrap();
刷新缓冲区
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;
流式发送
let _ = ctx
.set_response_header(CONTENT_TYPE, TEXT_EVENT_STREAM)
.await
.send()
.await;
for i in 1..10 {
let _ = ctx.set_response_body(format!("chunk {}\n", i)).await.send_body().await;
ctx.flush().await;
}
WebSocket 发送
pub async fn handle(ctx: Context) {
while ctx.ws_from_stream(4096).await.is_ok() {
let request_body: Vec<u8> = ctx.get_request_body().await;
ctx.set_response_body(&request_body).await;
let frame_list: Vec<ResponseBody> = WebSocketFrame::create_frame_list(&request_body);
ctx.send_body_list_with_data(&frame_list).await.unwrap();
}
}