weblib/lib.rs
1//! # weblib
2//!
3// `weblib` is a Rust library for making HTTP requests.
4//!
5//! ## Examples
6//!
7//! ```rust
8//! use weblib::text;
9//!
10//! fn main() {
11//! let url = "https://httpbin.org/get";
12//! let response = text(url).unwrap();
13//! println!("{}", response);
14//! }
15//! ```
16//!
17//! ## License
18//!
19//! This project is licensed under the terms of the GPL-3.0 license.
20//!
21//! ## Author
22//!
23//! This library was created by Mac Lawson.
24use reqwest::blocking::get;
25use reqwest::{RequestBuilder, Error};
26use reqwest::blocking::{Client, Response};
27use std::error::Error as OtherError;
28use std::time::Duration;
29
30
31/// Fetches the contents of a URL and returns them as a `String`.
32///
33/// # Arguments
34///
35/// * `url` - A string slice that holds the URL to fetch.
36///
37/// # Returns
38///
39/// This function returns a `Result` object that holds a `String` with the
40/// contents of the fetched URL, or an error message if the fetch fails.
41///
42/// # Examples
43///
44/// ```
45/// let url = "https://httpbin.org/ip";
46/// match weblib::text(url) {
47/// Ok(resp) => println!("{}", resp),
48/// Err(e) => panic!("Error: {}", e),
49/// }
50/// ```
51pub fn text(url: &str) -> Result<String, Box<dyn OtherError>> {
52 let resp = get(url)?.text()?;
53 Ok(resp)
54}
55
56
57/// Fetches the contents of a URL and returns them as a `String`.
58///
59/// # Arguments
60///
61/// * `url` - A string slice that holds the URL to fetch.
62///
63/// # Returns
64///
65/// This function returns a `Result` object that holds a `String` with the
66/// contents of the fetched URL, or an error message if the fetch fails.
67///
68/// # Examples
69///
70/// ```
71/// let url = "https://httpbin.org/get";
72/// let query = "key1=value1&key2=value2";
73/// match weblib::query(url, query) {
74/// Ok(resp) => println!("{}", resp),
75/// Err(e) => panic!("Error: {}", e),
76/// }
77/// ```
78pub fn query(url: &str, query_string: &str) -> Result<String, Box<dyn OtherError>> {
79 let url_with_query_string = format!("{}?{}", url, query_string);
80 let resp = get(&url_with_query_string)?.text()?;
81 Ok(resp)
82}
83
84
85/// Sends a POST request to the specified URL and returns the response as a `String`.
86///
87/// # Arguments
88///
89/// * `url` - A string slice that holds the URL to send the request to.
90/// * `data` - A string slice that holds the data to send in the request body.
91///
92/// # Returns
93///
94/// This function returns a `Result` object that holds a `String` with the
95/// contents of the response, or an error message if the request fails.
96///
97/// # Examples
98///
99/// ```
100/// let url = "https://httpbin.org/post";
101/// let data = "key1=value1&key2=value2";
102/// match weblib::post(url, data) {
103/// Ok(resp) => println!("{}", resp),
104/// Err(e) => panic!("Error: {}", e),
105/// }
106/// ```
107pub fn post(url: &str, data: &str) -> Result<String, Box<dyn OtherError>> {
108 let client = Client::new();
109 let resp = client.post(url).body(data.to_string()).send()?;
110 let body = resp.text()?;
111 Ok(body)
112}
113
114/// Fetches the contents of a URL using HTTP Basic authentication and returns them as a `String`.
115///
116/// # Arguments
117///
118/// * `url` - A string slice that holds the URL to fetch.
119/// * `username` - A string slice that holds the username for HTTP Basic authentication.
120/// * `password` - A string slice that holds the password for HTTP Basic authentication.
121///
122/// # Returns
123///
124/// This function returns a `Result` object that holds a `String` with the
125/// contents of the fetched URL, or an error message if the fetch fails.
126///
127/// # Examples
128///
129/// ```
130/// let url = "https://httpbin.org/basic-auth/user/passwd";
131/// match weblib::basic_auth(url, "user", "passwd") {
132/// Ok(resp) => println!("{}", resp),
133/// Err(e) => panic!("Error: {}", e),
134/// }
135/// ```
136pub fn basic_auth(url: &str, username: &str, password: &str) -> Result<String, Box<dyn OtherError>> {
137 let client = Client::new();
138 let resp = client
139 .request(reqwest::Method::GET, url)
140 .basic_auth(username, Some(password))
141 .send()?;
142 let body = resp.text()?;
143 Ok(body)
144}
145/// Send a request to the specified URL with retries and a timeout
146///
147/// # Arguments
148///
149/// * url - A string slice that holds the URL to be requested.
150/// * retries - The number of retries to perform in case of a request error.
151/// * timeout - The duration after which the request should timeout if it is not successful.
152///
153/// # Returns
154///
155/// * Result<Response, Error> - A Result type that holds the Response object on success or an Error object on failure.
156///
157/// # Examples
158///
159///
160/// use std::time::Duration;
161/// use weblib::request_with_retries;
162/// let url = "https://example.com";
163/// let retries = 3;
164/// let timeout = Duration::from_secs(10);
165/// match request_with_retries(url, retries, timeout) {
166/// Ok(response) => println!("Response: {:?}", response),
167/// Err(e) => println!("Error: {:?}", e),
168/// }
169///
170pub fn request_with_retries(
171 url: &str,
172 retries: usize,
173 timeout: Duration,
174) -> Result<Response, Error> {
175 let client = Client::builder()
176 .timeout(timeout)
177 .build()
178 .unwrap();
179
180 let mut response = client.get(url).send();
181
182 for _ in 1..retries {
183 match response {
184 Ok(res) => return Ok(res),
185 Err(e) => response = client.get(url).send(),
186 }
187 }
188
189 response
190}
191
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 #[test]
198 fn test_get_function_compiles() {
199 let url = "https://httpbin.org/ip";
200 match get(url) {
201 Ok(_) => assert!(true),
202 Err(e) => panic!("Error: {}", e),
203 }
204 }
205 #[test]
206 fn test_query_function() {
207 let url = "https://httpbin.org/get";
208 let query_string = "key1=value1&key2=value2";
209 let response = query(url, query_string).unwrap();
210 assert!(response.contains("\"key1\": \"value1\""));
211 assert!(response.contains("\"key2\": \"value2\""));
212 }
213 #[test]
214 fn test_post_function_compiles() {
215 let url = "https://httpbin.org/post";
216 let body = "test data";
217 let response = post(url, body);
218 assert!(response.is_ok());
219 }
220 #[test]
221 fn test_basic_auth_function_compiles() {
222 let url = "https://httpbin.org/basic-auth/user/passwd";
223 let username = "user";
224 let password = "passwd";
225 let _response = basic_auth(url, username, password);
226 }
227 #[test]
228 fn test_send_request_with_retries_compiles() {
229 let url = "https://example.com";
230 let retries = 3;
231 let timeout = Duration::from_secs(30);
232
233 let _result = request_with_retries(url, retries, timeout);
234 }
235
236
237
238
239}