A powerful HTTP networking package for MoonBit.
{
"deps": {
"oboard/mio": "0.3.0"
}
}@mio.run(fn() {
match (try? @mio.get("https://api.github.com")) {
Ok(response) => {
println("Status: " + response.statusCode.to_string())
println("Response: " + response.text())
}
Err(e) => println("Error: " + e.to_string())
}
})@mio.run(fn() {
match (try? @mio.post("https://httpbin.org/post",
data={
"name": "MoonBit",
"version": "0.3.0",
"features": ["async", "http", "json"]
})) {
Ok(response) => {
println("Posted successfully!")
println(response.unwrap_json())
}
Err(e) => println("Failed: " + e.to_string())
}
})@mio.run(fn() {
let headers = {
"Authorization": "Bearer your-token",
"User-Agent": "MoonBit-App/1.0",
"Accept": "application/json"
}
match (try? @mio.get("https://api.example.com/data",
headers=headers,
credentials=SameOrigin,
mode=CORS)) {
Ok(response) => {
if response.statusCode == 200 {
let data = response.json()
// Process your data
}
}
Err(e) => println("Request failed: " + e.to_string())
}
})@mio.run(fn() {
// Download with custom filename
match (try? @mio.download("https://api.github.com/repos/moonbitlang/core",
save_path="github_repo.json")) {
Ok(_) => println("File downloaded successfully!")
Err(e) => println("Download failed: " + e.to_string())
}
// Download with dynamic filename based on headers
match (try? @mio.download("https://example.com/file.zip",
save_path_fn=fn(headers) {
match headers.get("content-disposition") {
Some(disposition) => extract_filename(disposition)
None => "downloaded_file.zip"
}
})) {
Ok(_) => println("File downloaded with dynamic name!")
Err(e) => println("Download failed: " + e.to_string())
}
})@mio.run(fn() {
// Stream processing with real-time data handling
let chunks = []
match (try? @mio.get_stream("https://api.example.com/stream",
fn(chunk) {
println("Received chunk: " + chunk)
chunks.push(chunk)
// Process each chunk as it arrives
})) {
Ok(response) => {
println("Stream completed with status: " + response.statusCode.to_string())
println("Total chunks received: " + chunks.length().to_string())
}
Err(e) => println("Stream failed: " + e.to_string())
}
})// GET request
(try? @mio.get(url, headers?, credentials?, mode?))
// POST request with body or JSON data
(try? @mio.post(url, body?, data?, headers?, credentials?, mode?))
// Other HTTP methods
(try? @mio.put(url, body?, headers?, credentials?, mode?))
(try? @mio.delete(url, body?, headers?, credentials?, mode?))
(try? @mio.patch(url, body?, headers?, credentials?, mode?))
(try? @mio.options(url, body?, headers?, credentials?, mode?))
(try? @mio.head(url, body?, headers?, credentials?, mode?))
(try? @mio.connect(url, body?, headers?, credentials?, mode?))
(try? @mio.trace(url, body?, headers?, credentials?, mode?))
// Stream request with callback for real-time data processing
(try? @mio.get_stream(url, callback, headers?, credentials?, mode?))// HttpResponse methods
response.text() // Get response as string
response.json() // Parse JSON (may raise ParseError)
response.unwrap_json() // Safe JSON parsing (returns Json::null() on error)
response.statusCode // HTTP status code
response.headers // Response headers as Map[String, String]
response.data // Raw response data as Bytes@mio.run(fn() {
match (try? @mio.request("https://api.example.com/upload",
http_method=POST,
body="custom request body",
headers={
"Content-Type": "text/plain",
"X-Custom-Header": "value"
},
credentials=Include,
mode=CORS)) {
Ok(response) => {
// Handle response
}
Err(NetworkError) => {
// Handle network errors
}
}
})@mio.run(fn() {
// All requests return binary data in response.data
match (try? @mio.get("https://example.com/image.png")) {
Ok(response) => {
// response.data contains raw bytes (unified across all backends)
@fs.write_bytes_to_file("image.png", response.data)
// For text content, use response.text()
let text_content = response.text()
println("Content: " + text_content)
}
Err(e) => println("Failed to download: " + e.to_string())
}
})
pub suberror ExecError
pub suberror IOError
pub suberror UnimplementedError
impl Show for UnimplementedErrorpub(all) enum FetchCredentials {
Omit
SameOrigin
Include
}impl Eq for FetchCredentialsimpl Show for FetchCredentialsimpl ToJson for FetchCredentialspub(all) enum FetchMode {
CORS
NoCORS
SameOrigin
Navigate
}pub(all) enum HttpMethod {
GET
POST
PUT
DELETE
PATCH
OPTIONS
HEAD
CONNECT
TRACE
}impl Eq for HttpMethodimpl Show for HttpMethodimpl ToJson for HttpMethodpub(all) struct HttpRequest {
request_method : HttpMethod
url : String?
path : String
query : String?
body : Json?
}impl Eq for HttpRequestimpl Show for HttpRequestimpl ToJson for HttpRequestimpl Eq for HttpResponseimpl Show for HttpResponsefn HttpResponse::write_head(self : HttpResponse, statusCode : Int, headers : Map[String, String]) -> Unitpub struct SSEEvent {
event_type : String?
data : String
id : String?
retry : Int?
}async fn connect(url : String, body? : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn delete(url : String, body? : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn download(url : String, save_path? : String, save_path_fn? : (Map[String, String]) -> String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn get(url : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn get_stream(url : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode, on_chunk : (String) -> Unit) -> HttpResponse raise NetworkErrorasync fn head(url : String, body? : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn options(url : String, body? : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn patch(url : String, body? : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn post(url : String, body? : String, data? : Json, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn post_stream(url : String, data~ : Json, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode, on_chunk : (String) -> Unit) -> HttpResponse raise NetworkErrorasync fn put(url : String, body? : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Errorasync fn request(url : String, http_method? : HttpMethod, body? : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode, stream? : Bool) -> HttpResponse raise Errorasync fn request_internal_ffi(args : String) -> (String, String, Bytes) raise Errorasync fn request_stream(url : String, http_method? : HttpMethod, body? : Json, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode, on_chunk~ : (String) -> Unit) -> HttpResponse raise NetworkErrorasync fn request_stream_internal_ffi(args : String, on_chunk : (String) -> Unit) -> String raise Errorasync fn sse_connect(url : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode, on_event : (SSEEvent) -> Unit) -> HttpResponse raise Errorasync fn trace(url : String, body? : String, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse raise Error