import {
"q2316367743/moonhttp/transport",
}| 类型 | 内容 |
|---|---|
| Transport(trait) | 只有一个方法:async fn send(Self, PreparedRequest) -> RawResponse raise TransportError |
| PreparedRequest | 方法、完整 URL、拍平后的头、body 字节、超时、代理端点、上传进度回调、取消句柄 |
| RawResponse | 状态码、状态短语、响应头、响应体流 ResponseBody |
| ProxyEndpoint | { url, authorization? }:隧道地址与 CONNECT 的凭据 |
| TransportError | Timeout / Network(String) / Unsupported(String) / Cancelled;分类在根包翻译成 HttpError |
| 方法 | 说明 |
|---|---|
| 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)
Cancelled
}pub struct AsyncHttpTransport {
}impl Transport for AsyncHttpTransportasync fn send(self : AsyncHttpTransport, request : PreparedRequest) -> RawResponse raise TransportErrorasync fn AsyncHttpTransport::send(self : AsyncHttpTransport, request : PreparedRequest) -> RawResponse raise TransportErrorpub 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 : Bytes?
timeout : Int?
proxy : ProxyEndpoint?
on_upload_progress : (ProgressEvent) -> Unit?
cancel_token : CancelToken?
}impl Debug for PreparedRequestpub(all) struct RawResponse {
status : Int
status_text : String
headers : Headers
body : ResponseBody
} derive(Debug)pub struct ResponseBody {
// private fields
}impl Debug for 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 TransportErrorInstall
Download zipaxios 风格的 MoonBit HTTP 客户端:实例与配置合并、四种请求体形态、流式与 SSE、自动重定向
Dependencies