1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
//! # weblib
//!
// `weblib` is a Rust library for making HTTP requests.
//!
//! ## Examples
//!
//! ```rust
//! use weblib::text;
//!
//! fn main() {
//!     let url = "https://httpbin.org/get";
//!     let response = text(url).unwrap();
//!     println!("{}", response);
//! }
//! ```
//!
//! ## License
//!
//! This project is licensed under the terms of the GPL-3.0 license.
//!
//! ## Author
//!
//! This library was created by Mac Lawson.
use reqwest::blocking::get;
use reqwest::{RequestBuilder, Error};
use reqwest::blocking::{Client, Response};
use std::error::Error as OtherError;
use std::time::Duration;


/// Fetches the contents of a URL and returns them as a `String`.
///
/// # Arguments
///
/// * `url` - A string slice that holds the URL to fetch.
///
/// # Returns
///
/// This function returns a `Result` object that holds a `String` with the
/// contents of the fetched URL, or an error message if the fetch fails.
///
/// # Examples
///
/// ```
/// let url = "https://httpbin.org/ip";
/// match weblib::text(url) {
///     Ok(resp) => println!("{}", resp),
///     Err(e) => panic!("Error: {}", e),
/// }
/// ```
pub fn text(url: &str) -> Result<String, Box<dyn OtherError>> {
    let resp = get(url)?.text()?;
    Ok(resp)
}


/// Fetches the contents of a URL and returns them as a `String`.
///
/// # Arguments
///
/// * `url` - A string slice that holds the URL to fetch.
///
/// # Returns
///
/// This function returns a `Result` object that holds a `String` with the
/// contents of the fetched URL, or an error message if the fetch fails.
///
/// # Examples
///
/// ```
/// let url = "https://httpbin.org/get";
/// let query = "key1=value1&key2=value2";
/// match weblib::query(url, query) {
///     Ok(resp) => println!("{}", resp),
///     Err(e) => panic!("Error: {}", e),
/// }
/// ```
pub fn query(url: &str, query_string: &str) -> Result<String, Box<dyn OtherError>> {
    let url_with_query_string = format!("{}?{}", url, query_string);
    let resp = get(&url_with_query_string)?.text()?;
    Ok(resp)
}


/// Sends a POST request to the specified URL and returns the response as a `String`.
///
/// # Arguments
///
/// * `url` - A string slice that holds the URL to send the request to.
/// * `data` - A string slice that holds the data to send in the request body.
///
/// # Returns
///
/// This function returns a `Result` object that holds a `String` with the
/// contents of the response, or an error message if the request fails.
///
/// # Examples
///
/// ```
/// let url = "https://httpbin.org/post";
/// let data = "key1=value1&key2=value2";
/// match weblib::post(url, data) {
///     Ok(resp) => println!("{}", resp),
///     Err(e) => panic!("Error: {}", e),
/// }
/// ```
pub fn post(url: &str, data: &str) -> Result<String, Box<dyn OtherError>> {
    let client = Client::new();
    let resp = client.post(url).body(data.to_string()).send()?;
    let body = resp.text()?;
    Ok(body)
}

/// Fetches the contents of a URL using HTTP Basic authentication and returns them as a `String`.
///
/// # Arguments
///
/// * `url` - A string slice that holds the URL to fetch.
/// * `username` - A string slice that holds the username for HTTP Basic authentication.
/// * `password` - A string slice that holds the password for HTTP Basic authentication.
///
/// # Returns
///
/// This function returns a `Result` object that holds a `String` with the
/// contents of the fetched URL, or an error message if the fetch fails.
///
/// # Examples
///
/// ```
/// let url = "https://httpbin.org/basic-auth/user/passwd";
/// match weblib::basic_auth(url, "user", "passwd") {
///     Ok(resp) => println!("{}", resp),
///     Err(e) => panic!("Error: {}", e),
/// }
/// ```
pub fn basic_auth(url: &str, username: &str, password: &str) -> Result<String, Box<dyn OtherError>> {
    let client = Client::new();
    let resp = client
        .request(reqwest::Method::GET, url)
        .basic_auth(username, Some(password))
        .send()?;
    let body = resp.text()?;
    Ok(body)
}
/// Send a request to the specified URL with retries and a timeout
///
/// # Arguments
///
/// * url - A string slice that holds the URL to be requested.
/// * retries - The number of retries to perform in case of a request error.
/// * timeout - The duration after which the request should timeout if it is not successful.
///
/// # Returns
///
/// * Result<Response, Error> - A Result type that holds the Response object on success or an Error object on failure.
///
/// # Examples
///
/// 
/// use std::time::Duration; 
/// use weblib::request_with_retries; 
/// let url = "https://example.com";
/// let retries = 3; 
/// let timeout = Duration::from_secs(10);
/// match request_with_retries(url, retries, timeout) { 
/// Ok(response) => println!("Response: {:?}", response), 
/// Err(e) => println!("Error: {:?}", e), 
/// } 
///
pub fn request_with_retries(
    url: &str,
    retries: usize,
    timeout: Duration,
) -> Result<Response, Error> {
    let client = Client::builder()
        .timeout(timeout)
        .build()
        .unwrap();

    let mut response = client.get(url).send();

    for _ in 1..retries {
        match response {
            Ok(res) => return Ok(res),
            Err(e) => response = client.get(url).send(),
        }
    }

    response
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_function_compiles() {
        let url = "https://httpbin.org/ip";
        match get(url) {
            Ok(_) => assert!(true),
            Err(e) => panic!("Error: {}", e),
        }
    }
    #[test]
    fn test_query_function() {
        let url = "https://httpbin.org/get";
        let query_string = "key1=value1&key2=value2";
        let response = query(url, query_string).unwrap();
        assert!(response.contains("\"key1\": \"value1\""));
        assert!(response.contains("\"key2\": \"value2\""));
    }
    #[test]
    fn test_post_function_compiles() {
        let url = "https://httpbin.org/post";
        let body = "test data";
        let response = post(url, body);
        assert!(response.is_ok());
    }
    #[test]
    fn test_basic_auth_function_compiles() {
        let url = "https://httpbin.org/basic-auth/user/passwd";
        let username = "user";
        let password = "passwd";
        let _response = basic_auth(url, username, password);
    }
    #[test]
    fn test_send_request_with_retries_compiles() {
        let url = "https://example.com";
        let retries = 3;
        let timeout = Duration::from_secs(30);
    
        let _result = request_with_retries(url, retries, timeout);
    }
    
    
    

}