import {
"q2316367743/moonhttp/transport",
}| 类型 | 内容 |
|---|---|
| Transport(trait) | 只有一个方法:async fn send(Self, PreparedRequest) -> RawResponse raise TransportError |
| PreparedRequest | 方法、完整 URL、拍平后的头、body(RequestBody?:Buffered(Bytes) 或 Stream(StreamBody))、超时、代理端点、上传进度回调、取消信号 |
| RawResponse | 状态码、状态短语、响应头、响应体流 ResponseBody |
| ProxyEndpoint | { url, authorization? }:隧道地址与 CONNECT 的凭据 |
| TransportError | Timeout / Network(String) / Unsupported(String) / Malformed(String) / Cancelled(String?);上层看到的 HttpError 分类就来自它(Malformed 是「响应体与它声称的 Content-Encoding 不符」,报 ERR_BAD_RESPONSE),取消的载荷是取消理由 |
| 方法 | 说明 |
|---|---|
| from_bytes(bytes) | 手里已有完整响应体时包一层(Mock 与测试用) |
| read_all(on_progress?) | 读到 EOF;传了回调就逐块报下载进度 |
| read_all_partial(on_progress?) | 同上但不抛错:返回 (已读到的字节, 失败原因?),「读到一半失败」时保住现场 |
| read_some(max_len?) | 读一块,None 表示 EOF |
| read_until(delim) | 读到分隔符(含分隔符)为止 |
| close() | 释放连接 |
// 在测试里替换掉真实网络
///|
let mock = @transport.MockTransport::new(response)
///|
let transport : &@transport.Transport = mock
///|
let client = @moonhttp.Client::new(transport~)///|
pub impl Transport for MyTransport with fn send(self, request) {
// request : PreparedRequest(方法、完整地址、已拍平的头、body(缓冲或流式)、超时)
// 返回 : RawResponse(状态码、状态短语、响应头、响应体流)
...
}pub(open) trait Transport {
async fn send(Self, PreparedRequest) -> RawResponse raise TransportError
}pub(all) suberror TransportError {
Timeout
Network(String)
Unsupported(String)
Malformed(String)
Cancelled(String?)
}pub struct MockTransport {
// private fields
}impl Transport for MockTransportasync fn MockTransport::send(self : MockTransport, request : PreparedRequest) -> RawResponse raise TransportErrorpub(all) struct PreparedRequest {
http_method : Method
url : String
headers : Headers
body : RequestBody?
timeout : Int?
proxy : ProxyEndpoint?
on_upload_progress : (ProgressEvent) -> Unit?
signal : AbortSignal?
}impl Debug for PreparedRequestpub(all) struct RawResponse {
status : Int
status_text : String
headers : Headers
body : ResponseBody
set_cookies : Array[String]
} derive(Debug)pub struct ResponseBody {
// private fields
}impl Debug for ResponseBodyfn ResponseBody::open_wire(reader : &Reader, close : () -> Unit, timeout~ : Int?, total~ : Int?, signal~ : AbortSignal?) -> ResponseBodyasync fn ResponseBody::read_all(self : ResponseBody, on_progress? : (ProgressEvent) -> Unit) -> Bytes raise TransportErrorasync fn ResponseBody::read_all_partial(self : ResponseBody, on_progress? : (ProgressEvent) -> Unit) -> (Bytes, TransportError?) noraiseasync fn ResponseBody::read_some(self : ResponseBody, max_len? : Int) -> Bytes? raise TransportErrorasync fn ResponseBody::read_until(self : ResponseBody, sep : String) -> String? raise TransportErrorasync fn[T] with_abort_scope(signal : AbortSignal?, f : async () -> T raise TransportError) -> T raise TransportErrorInstall
Download zipaxios 风格的 MoonBit HTTP 客户端:实例与配置合并、四种请求体形态、流式与 SSE、自动重定向
Dependencies