feat: update fetch-rs

This commit is contained in:
2023-06-04 14:09:25 +08:00
parent c259d6c102
commit 8aba71a72b
2 changed files with 65 additions and 22 deletions

View File

@@ -1,18 +1,34 @@
```js ```rust
const response = fetch("http://example.com/movies.json") let response = fetch(
const responseJson = response.json(); "https://hatter.ink/util/print_request.action",
&FetchOptions::default())?;
``` ```
```js ```rust
const response = fetch(url, { let response = fetch(
method: "POST", // *GET, POST, PUT, DELETE, etc. "https://hatter.ink/util/print_request.action",
headers: { &FetchOptions {
"Content-Type": "application/json", method: FetchMethod::Put,
// 'Content-Type': 'application/x-www-form-urlencoded', body: Some("{}".as_bytes().to_vec()),
}, ..Default::default()
redirect: "follow", // manual, *follow, error })?;
body: JSON.stringify(data), // body data type must match "Content-Type" header ```
});
```rust
let response = fetch(
"https://hatter.ink/util/print_request.action",
&FetchOptions {
method: FetchMethod::Post,
headers: Some(vec![
FetchHeader {
key: "content-type".to_string(),
value: "application/json".to_string(),
}
]),
body: Some("{}".as_bytes().to_vec()),
..Default::default()
})?;
``` ```

View File

@@ -1,12 +1,29 @@
use std::str::FromStr; use std::str::FromStr;
use std::time::Duration; use std::time::Duration;
use reqwest::{Method, Url}; use reqwest::{Method, Proxy, Url};
use reqwest::blocking::{Body, Client, Request}; use reqwest::blocking::{Body, Client, Request};
use reqwest::header::{HeaderName, HeaderValue}; use reqwest::header::{HeaderName, HeaderValue};
use rust_util::{simple_error, XResult}; use rust_util::{simple_error, XResult};
fn main() -> XResult<()> { fn main() -> XResult<()> {
println!("TEST1: GET");
let response = fetch(
"https://hatter.ink/util/print_request.action",
&FetchOptions::default())?;
print_response(&response)?;
println!("TEST2: PUT");
let response = fetch(
"https://hatter.ink/util/print_request.action",
&FetchOptions {
method: FetchMethod::Put,
body: Some("{}".as_bytes().to_vec()),
..Default::default()
})?;
print_response(&response)?;
println!("TEST3: POST");
let response = fetch( let response = fetch(
"https://hatter.ink/util/print_request.action", "https://hatter.ink/util/print_request.action",
&FetchOptions { &FetchOptions {
@@ -20,9 +37,15 @@ fn main() -> XResult<()> {
body: Some("{}".as_bytes().to_vec()), body: Some("{}".as_bytes().to_vec()),
..Default::default() ..Default::default()
})?; })?;
print_response(&response)?;
Ok(())
}
fn print_response(response: &FetchResponse) -> XResult<()> {
println!("Status: {}", response.status); println!("Status: {}", response.status);
response.headers.iter().for_each(|h| { response.headers.iter().for_each(|_h| {
println!("- {}: {}", h.key, h.value); // println!("- {}: {}", h.key, h.value);
}); });
println!("----- BEGIN RESPONSE BODY -----\n{}\n----- END RESPONSE BODY -----", println!("----- BEGIN RESPONSE BODY -----\n{}\n----- END RESPONSE BODY -----",
String::from_utf8(response.body().clone().unwrap().to_vec())?); String::from_utf8(response.body().clone().unwrap().to_vec())?);
@@ -62,10 +85,11 @@ pub struct FetchOptions {
pub method: FetchMethod, pub method: FetchMethod,
pub headers: Option<Vec<FetchHeader>>, pub headers: Option<Vec<FetchHeader>>,
pub body: Option<Vec<u8>>, pub body: Option<Vec<u8>>,
// connect timeout or read timeout? // FIXME connect timeout or read timeout?
pub timeout: Option<Duration>, pub timeout: Option<Duration>,
// proxy supports pub proxy: Option<String>,
// hsts supports // TODO hsts supports
// TODO follow redirects?
} }
impl FetchOptions {} impl FetchOptions {}
@@ -96,9 +120,12 @@ impl FetchResponse {
} }
pub fn fetch(url: &str, option: &FetchOptions) -> XResult<FetchResponse> { pub fn fetch(url: &str, option: &FetchOptions) -> XResult<FetchResponse> {
let client = Client::builder() let mut client_builder = Client::builder();
// .proxy() if let Some(proxy) = &option.proxy {
.build()?; client_builder = client_builder.proxy(Proxy::all(proxy.as_str())?);
}
// TODO client_builder.add_root_certificate()
let client = client_builder.build()?;
let method = match option.method { let method = match option.method {
FetchMethod::Get => Method::GET, FetchMethod::Get => Method::GET,
FetchMethod::Post => Method::POST, FetchMethod::Post => Method::POST,