import {
"q2316367743/moonhttp/config",
}///|
let config = Config::new("/users") // 带 url 起步
///|
let defaults = Config::default() // 从零起步
.with_base_url("https://api.example.com")
.with_timeout(5_000)| 方法 | 说明 |
|---|---|
| with_url(url) | 请求地址:相对地址与 base_url 拼接,绝对地址直连 |
| with_base_url(url) | 基地址,通常写在实例默认值里 |
| with_method(Method) | 请求方法,缺省回退到 GET |
| with_allow_absolute_urls(bool) | 是否允许绝对地址直连(默认 true) |
| 方法 | 说明 |
|---|---|
| with_timeout(ms) | 超时毫秒数,0 表示不超时(默认) |
| with_max_redirects(n) | 最多跟几跳重定向,默认 5,0 表示不跟随 |
| 方法 | 说明 |
|---|---|
| with_header(name, value) | 本次请求的头 |
| with_headers(Headers) | 一次性给一组头 |
| with_common_header(name, value) | 公共头:该实例的所有方法都带上 |
| with_method_header(Method, name, value) | 按方法区分的头(如只给 Post 加 Content-Type) |
| 方法 | 说明 |
|---|---|
| with_params(Json) | 查询参数,数组与嵌套对象按括号约定展开 |
| with_params_serializer(fn(Json) -> String) | 整体替换「params → query 文本」这一步(只作用于 URL 的 query) |
| 方法 | 说明 | 自动补的 Content-Type |
|---|---|---|
| with_data_from_str(String) | 原样 UTF-8 字节 | 不补 |
| with_data_from_json(Json) | stringify() 后的 JSON 文本 | application/json |
| with_data_from_urlencoded(Json) | a=1&b=2 | application/x-www-form-urlencoded |
| with_data_from_form(FormData) | multipart 正文 | multipart/form-data; boundary=... |
| 方法 | 说明 |
|---|---|
| with_auth(username, password) | Basic 认证,落成 Authorization 头 |
| with_proxy(host, port?, protocol?, username?, password?) | 代理;凭据只落在建隧道的 CONNECT 上,不发给目标服务器 |
| 方法 | 说明 |
|---|---|
| with_on_upload_progress(cb) | 上传进度回调(同步、不抛错) |
| with_on_download_progress(cb) | 下载进度回调 |
| with_cancel_token(CancelToken) | 绑定取消句柄 |
| 方法 | 说明 |
|---|---|
| with_response_encoding(ResponseEncoding) | 响应体按什么解码,默认 Utf8 |
| with_validate_status(fn(Int) -> Bool) | 状态码校验规则,默认「2xx 算成功」 |
| 方法 | 说明 |
|---|---|
| Config::new(url) / Config::default() | 构造 |
| serialize_body() | 请求体 → 字节 + 建议的 Content-Type(SerializedBody) |
| next_redirect(location, status, method?) | 算重定向的下一跳配置(方法、请求体、凭据、Host 的改写规则) |
| to_string() / output(logger) / to_repr() | 渲染(Show / Debug) |
| 类型 | 说明 |
|---|---|
| Method | Get / Head / Post / Put / Delete / Connect / Options / Trace / Patch,另有 Method::parse(view) |
| ResponseEncoding | Utf8(默认)/ Latin1 / Ascii / Utf16le |
| Auth | { username?, password? },Basic 凭据 |
| Proxy / ProxyProtocol | { protocol?, host?, port?, auth? };Proxy::is_usable() 判断「配了代理但没给 host」 |
| FormData / FormValue / FormFile | new() / append_text(name, value) / append_file(name, filename, bytes, content_type?) / entries() / length() |
| CancelToken | new() / cancel(message?) / is_cancelled() / reason() / attach(cb) / detach(id) |
| ProgressEvent / ProgressCallback | { loaded, total? } + progress()(total 未知或为 0 时给 None) |
| SerializedBody | { bytes?, content_type? } |
| 函数 | 说明 |
|---|---|
| defaults() | 内置默认值:timeout = 0(不超时)、max_redirects = 5、response_encoding = Utf8、validate_status = 2xx、Accept: application/json, text/plain, */*、allow_absolute_urls = true |
| merge_config(默认值, 请求级) | 请求级配置合并在实例默认值之上 |
| flatten_headers(公共头?, 按方法的头?, 请求级头?, 方法) | 三层头拍平成一份 |
| merge_json(a, b) / merge_json_option(a, b) | JSON 深合并(params 用它) |
| 字段 | 策略 |
|---|---|
| url / http_method / 请求体 | 只取请求级 |
| base_url / timeout / max_redirects / response_encoding / 进度回调 / cancel_token | 请求级优先,缺省回退实例默认值 |
| params / headers / auth / proxy | 逐层深合并(数组整体替换,函数没法合并所以整体接管) |
| validate_status / params_serializer | 请求级提供即整体接管 |
pub struct CancelToken {
// private fields
}pub(all) struct Config {
url : String?
http_method : Method?
base_url : String?
timeout : Int?
max_redirects : Int?
response_encoding : ResponseEncoding?
params : Json?
params_serializer : (Json) -> String?
on_upload_progress : (ProgressEvent) -> Unit?
on_download_progress : (ProgressEvent) -> Unit?
cancel_token : CancelToken?
auth : Auth?
proxy : Proxy?
headers : Headers?
common_headers : Headers?
method_headers : Map[Method, Headers]?
validate_status : (Int) -> Bool?
allow_absolute_urls : Bool?
// private fields
} derive(Default)let token = CancelToken::new()
let config = Config::new("/reports/big.csv")
.with_cancel_token(token)
// 另一处(另一个协程、或某个 UI 回调里):
token.cancel(message="用户点了停止")@moonhttp.Config::new("/login")
.with_data_from_str("user=alice&password=s3cret")
.with_header("Content-Type", "application/x-www-form-urlencoded")fn Config::with_on_download_progress(self : Config, on_download_progress : (ProgressEvent) -> Unit) -> Configfn Config::with_on_upload_progress(self : Config, on_upload_progress : (ProgressEvent) -> Unit) -> ConfigConfig::new("/upload")
.with_data_from_form(form)
.with_on_upload_progress(fn(event) {
println("\{event.loaded} / \{event.total.unwrap_or(0)}")
})Config::new("/search")
.with_params({ "tags": ["a", "b"] })
.with_params_serializer(fn(_params) { "tags=a&tags=b" })fn Config::with_proxy(self : Config, host : String, port? : Int, protocol? : ProxyProtocol, username? : String, password? : String) -> ConfigConfig::default().with_proxy("127.0.0.1", port=9000)
Config::default().with_proxy(
"proxy.corp", port=8443, protocol=ProxyProtocol::Https,
username="mikeymike", password="rapunz3l",
)let config = Config::default()
.with_base_url("https://api.example.com")
.with_timeout(5000)pub struct FormData {
// private fields
}@moonhttp.FormData::new()
.append_text("title", "假期照片")
.append_file("avatar", "a.png", bytes, content_type="image/png")pub(all) struct FormFile {
filename : String
content_type : String
bytes : Bytes
}pub(all) struct Proxy {
protocol : ProxyProtocol?
host : String?
port : Int?
auth : Auth?
} derive(Default, Eq, Debug)pub(all) struct SerializedBody {
bytes : Bytes?
content_type : String?
}Install
Download zipaxios 风格的 MoonBit HTTP 客户端:实例与配置合并、四种请求体形态、流式与 SSE、自动重定向
Dependencies