pub struct Client;Expand description
Main client for making HTTP requests
Implementations§
Source§impl Client
impl Client
Sourcepub fn get(&self, url: impl Into<String>) -> RequestBuilder
pub fn get(&self, url: impl Into<String>) -> RequestBuilder
Make a GET request
Examples found in repository?
examples/github_api.rs (line 34)
29async fn get_github_branch_advanced(repo: String) -> Result<GitHubBranch> {
30 let client = Client;
31 let url = format!("https://api.github.com/repos/{}/branches/master", repo);
32
33 let response = client
34 .get(url)
35 .header("Accept", "application/vnd.github.v3+json")
36 .header("User-Agent", "rust-wasm-fetch")
37 .send()
38 .await?
39 .error_for_status()?;
40
41 response.json().await
42}More examples
examples/streaming.rs (line 15)
9pub async fn stream_large_file() {
10 let client = Client;
11 let url = "https://raw.githubusercontent.com/yaptown/yap/refs/heads/main/out/deu/frequency_lists/combined/frequencies.jsonl";
12
13 console::log_1(&"Starting streaming download...".into());
14
15 let response = match client.get(url).send().await {
16 Ok(r) => r,
17 Err(e) => {
18 console::error_1(&format!("Request failed: {}", e).into());
19 return;
20 }
21 };
22
23 let response = match response.error_for_status() {
24 Ok(r) => r,
25 Err(e) => {
26 console::error_1(&format!("HTTP error: {}", e).into());
27 return;
28 }
29 };
30
31 // Get a stream reader
32 let reader = match response.stream_reader() {
33 Ok(r) => r,
34 Err(e) => {
35 console::error_1(&format!("Failed to get stream reader: {}", e).into());
36 return;
37 }
38 };
39
40 let mut total_bytes = 0;
41 let mut chunk_count = 0;
42
43 // Read chunks until the stream is done
44 loop {
45 match reader.read_chunk().await {
46 Ok(Some(chunk)) => {
47 total_bytes += chunk.len();
48 chunk_count += 1;
49 console::log_1(&format!("Received chunk {}: {} bytes", chunk_count, chunk.len()).into());
50 }
51 Ok(None) => break,
52 Err(e) => {
53 console::error_1(&format!("Error reading chunk: {}", e).into());
54 return;
55 }
56 }
57 }
58
59 console::log_1(&format!("✓ Total: {} bytes in {} chunks", total_bytes, chunk_count).into());
60}
61
62/// Example of streaming text content line by line
63#[wasm_bindgen]
64pub async fn stream_text_content() {
65 let client = Client;
66 let url = "https://raw.githubusercontent.com/yaptown/yap/refs/heads/main/out/deu/frequency_lists/combined/frequencies.jsonl";
67
68 console::log_1(&"Starting line-by-line streaming...".into());
69
70 let response = match client.get(url).send().await.and_then(|r| r.error_for_status()) {
71 Ok(r) => r,
72 Err(e) => {
73 console::error_1(&format!("Request failed: {}", e).into());
74 return;
75 }
76 };
77
78 let reader = match response.stream_reader() {
79 Ok(r) => r,
80 Err(e) => {
81 console::error_1(&format!("Failed to get stream reader: {}", e).into());
82 return;
83 }
84 };
85
86 let mut buffer = Vec::new();
87 let mut line_count = 0;
88
89 loop {
90 let chunk = match reader.read_chunk().await {
91 Ok(Some(c)) => c,
92 Ok(None) => break,
93 Err(e) => {
94 console::error_1(&format!("Error reading chunk: {}", e).into());
95 return;
96 }
97 };
98
99 buffer.extend_from_slice(&chunk);
100
101 // Process complete lines from the buffer
102 while let Some(newline_pos) = buffer.iter().position(|&b| b == b'\n') {
103 let line_bytes = buffer.drain(..=newline_pos).collect::<Vec<_>>();
104 let line = String::from_utf8_lossy(&line_bytes);
105 line_count += 1;
106
107 // Only log first few lines to avoid spam
108 if line_count <= 5 {
109 console::log_1(&format!("Line {}: {}", line_count, line.trim()).into());
110 }
111 }
112 }
113
114 // Process any remaining data in the buffer
115 if !buffer.is_empty() {
116 let line = String::from_utf8_lossy(&buffer);
117 line_count += 1;
118 console::log_1(&format!("Last line: {}", line.trim()).into());
119 }
120
121 console::log_1(&format!("✓ Processed {} lines total", line_count).into());
122}
123
124/// Example of downloading with progress tracking
125#[wasm_bindgen]
126pub async fn download_with_progress() {
127 let client = Client;
128 let url = "https://raw.githubusercontent.com/yaptown/yap/refs/heads/main/out/deu/frequency_lists/combined/frequencies.jsonl";
129
130 console::log_1(&"Starting download with progress tracking...".into());
131
132 let response = match client.get(url).send().await.and_then(|r| r.error_for_status()) {
133 Ok(r) => r,
134 Err(e) => {
135 console::error_1(&format!("Request failed: {}", e).into());
136 return;
137 }
138 };
139
140 // Get content length if available
141 let content_length = response
142 .header("content-length")
143 .ok()
144 .flatten()
145 .and_then(|s| s.parse::<usize>().ok());
146
147 if let Some(total) = content_length {
148 console::log_1(&format!("Content-Length: {} bytes", total).into());
149 } else {
150 console::log_1(&"Content-Length not available".into());
151 }
152
153 let reader = match response.stream_reader() {
154 Ok(r) => r,
155 Err(e) => {
156 console::error_1(&format!("Failed to get stream reader: {}", e).into());
157 return;
158 }
159 };
160
161 let mut downloaded = Vec::new();
162 let mut last_logged_percent = 0;
163
164 loop {
165 let chunk = match reader.read_chunk().await {
166 Ok(Some(c)) => c,
167 Ok(None) => break,
168 Err(e) => {
169 console::error_1(&format!("Error reading chunk: {}", e).into());
170 return;
171 }
172 };
173
174 downloaded.extend_from_slice(&chunk);
175
176 if let Some(total) = content_length {
177 let progress = (downloaded.len() as f64 / total as f64) * 100.0;
178 let progress_int = progress as u32;
179
180 // Only log every 10%
181 if progress_int >= last_logged_percent + 10 {
182 console::log_1(&format!("Progress: {:.1}% ({}/{})", progress, downloaded.len(), total).into());
183 last_logged_percent = progress_int;
184 }
185 }
186 }
187
188 console::log_1(&format!("✓ Download complete: {} bytes", downloaded.len()).into());
189}Sourcepub fn post(&self, url: impl Into<String>) -> RequestBuilder
pub fn post(&self, url: impl Into<String>) -> RequestBuilder
Make a POST request
Examples found in repository?
examples/github_api.rs (line 58)
51async fn create_github_issue(repo: String, title: String, body: String) -> Result<Value> {
52 let client = Client;
53 let url = format!("https://api.github.com/repos/{}/issues", repo);
54
55 let issue = CreateIssue { title, body };
56
57 let response = client
58 .post(url)
59 .header("Accept", "application/vnd.github.v3+json")
60 .header("Authorization", "token YOUR_GITHUB_TOKEN")
61 .json(&issue)?
62 .send()
63 .await?
64 .error_for_status()?;
65
66 response.json_value().await
67}Sourcepub fn put(&self, url: impl Into<String>) -> RequestBuilder
pub fn put(&self, url: impl Into<String>) -> RequestBuilder
Make a PUT request
Sourcepub fn delete(&self, url: impl Into<String>) -> RequestBuilder
pub fn delete(&self, url: impl Into<String>) -> RequestBuilder
Make a DELETE request
Sourcepub fn patch(&self, url: impl Into<String>) -> RequestBuilder
pub fn patch(&self, url: impl Into<String>) -> RequestBuilder
Make a PATCH request
Sourcepub fn head(&self, url: impl Into<String>) -> RequestBuilder
pub fn head(&self, url: impl Into<String>) -> RequestBuilder
Make a HEAD request
Auto Trait Implementations§
impl Freeze for Client
impl RefUnwindSafe for Client
impl Send for Client
impl Sync for Client
impl Unpin for Client
impl UnsafeUnpin for Client
impl UnwindSafe for Client
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more