http-type 4.37.0

A library providing essential types for HTTP, including request bodies, response headers, and other core HTTP abstractions.
Documentation
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use crate::*;

impl Default for Response {
    fn default() -> Self {
        Self::new()
    }
}

impl Response {
    /// Creates a new instance of `Response`.
    ///
    /// # Returns
    /// - An initialized `Response` with default values.
    pub fn new() -> Self {
        Response {
            version: HttpVersion::HTTP1_1,
            status_code: 200,
            reason_phrase: EMPTY_STR.to_owned(),
            headers: hash_map_xx_hash3_64(),
            body: Vec::new(),
        }
    }

    /// Retrieves the value of a response header by its key.
    ///
    /// # Parameters
    /// - `key`: The header's key, which can be of any type that implements `Into<ResponseHeadersKey>`.
    ///
    /// # Returns
    /// - `OptionResponseHeadersValue`: Returns `Some(value)` if the key exists in the response headers,
    ///   or `None` if the key does not exist.
    pub fn get_header<K>(&self, key: K) -> OptionResponseHeadersValue
    where
        K: Into<ResponseHeadersKey>,
    {
        self.headers
            .get(&key.into())
            .and_then(|data| Some(data.clone()))
    }

    /// Retrieves the first value of a response header by its key.
    ///
    /// # Parameters
    /// - `key`: The header's key, which can be of any type that implements `Into<ResponseHeadersKey>`.
    ///
    /// # Returns
    /// - `OptionResponseHeadersValueItem`: Returns `Some(value)` if the key exists and has at least one value,
    ///   or `None` if the key does not exist or has no values.
    pub fn get_header_front<K>(&self, key: K) -> OptionResponseHeadersValueItem
    where
        K: Into<ResponseHeadersKey>,
    {
        self.headers
            .get(&key.into())
            .and_then(|values| values.front().cloned())
    }

    /// Retrieves the last value of a response header by its key.
    ///
    /// # Parameters
    /// - `key`: The header's key, which can be of any type that implements `Into<ResponseHeadersKey>`.
    ///
    /// # Returns
    /// - `OptionResponseHeadersValueItem`: Returns `Some(value)` if the key exists and has at least one value,
    ///   or `None` if the key does not exist or has no values.
    pub fn get_header_back<K>(&self, key: K) -> OptionResponseHeadersValueItem
    where
        K: Into<ResponseHeadersKey>,
    {
        self.headers
            .get(&key.into())
            .and_then(|values| values.back().cloned())
    }

    /// Checks if a header exists in the response.
    ///
    /// # Parameters
    /// - `key`: The header key to check, which will be converted into a `ResponseHeadersKey`.
    ///
    /// # Returns
    /// - `true`: If the header exists.
    /// - `false`: If the header does not exist.
    pub fn has_header<K>(&self, key: K) -> bool
    where
        K: Into<ResponseHeadersKey>,
    {
        let key: ResponseHeadersKey = key.into().to_lowercase();
        self.headers.contains_key(&key)
    }

    /// Checks if a header contains a specific value.
    ///
    /// # Parameters
    /// - `key`: The header key to check, which will be converted into a `ResponseHeadersKey`.
    /// - `value`: The value to search for in the header.
    ///
    /// # Returns
    /// - `true`: If the header exists and contains the specified value.
    /// - `false`: If the header does not exist or does not contain the value.
    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
    where
        K: Into<ResponseHeadersKey>,
        V: Into<ResponseHeadersValueItem>,
    {
        let key: ResponseHeadersKey = key.into();
        let value: ResponseHeadersValueItem = value.into();
        if let Some(values) = self.headers.get(&key) {
            values.contains(&value)
        } else {
            false
        }
    }

    /// Gets the number of headers in the response.
    ///
    /// # Returns
    /// - The number of unique header keys in the response.
    pub fn get_headers_len(&self) -> usize {
        self.headers.len()
    }

    /// Gets the number of values for a specific header key.
    ///
    /// # Parameters
    /// - `key`: The header key to count values for, which will be converted into a `ResponseHeadersKey`.
    ///
    /// # Returns
    /// - The number of values for the specified header key. Returns 0 if the header does not exist.
    pub fn get_header_len<K>(&self, key: K) -> usize
    where
        K: Into<ResponseHeadersKey>,
    {
        let key: ResponseHeadersKey = key.into().to_lowercase();
        self.headers.get(&key).map_or(0, |values| values.len())
    }

    /// Gets the total number of header values in the response.
    ///
    /// This counts all values across all headers, so a header with multiple values
    /// will contribute more than one to the total count.
    ///
    /// # Returns
    /// - The total number of header values in the response.
    pub fn get_headers_values_len(&self) -> usize {
        self.headers.values().map(|values| values.len()).sum()
    }

    /// Retrieves the body content of the object as a UTF-8 encoded string.
    ///
    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` into a string.
    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character (�).
    ///
    /// # Returns
    /// A `String` containing the body content.
    pub fn get_body_string(&self) -> String {
        String::from_utf8_lossy(self.get_body()).into_owned()
    }

    /// Deserializes the body content of the object into a specified type `T`.
    ///
    /// This method first retrieves the body content as a UTF-8 encoded string using `self.get_body()`.
    /// It then attempts to deserialize the string into the specified type `T` using `json_from_slice`.
    ///
    /// # Type Parameters
    /// - `T`: The target type to deserialize into. It must implement the `DeserializeOwned` trait.
    ///
    /// # Returns
    /// - `Ok(T)`: The deserialized object of type `T` if the deserialization is successful.
    /// - `Err(ResultJsonError)`: An error if the deserialization fails (e.g., invalid JSON format or type mismatch).
    pub fn get_body_json<T>(&self) -> ResultJsonError<T>
    where
        T: DeserializeOwned,
    {
        json_from_slice(self.get_body())
    }

    /// Adds a header to the response.
    ///
    /// This function appends a value to the response headers.
    /// If the header already exists, the new value will be added to the existing values.
    ///
    /// # Parameters
    /// - `key`: The header key, which will be converted into a `ResponseHeadersKey`.
    /// - `value`: The value of the header, which will be converted into a String.
    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
    where
        K: Into<ResponseHeadersKey>,
        V: Into<String>,
    {
        let key: ResponseHeadersKey = key.into().to_lowercase();
        if key.trim().is_empty() || key == CONTENT_LENGTH {
            return self;
        }
        let value: String = value.into();
        self.headers
            .entry(key)
            .or_insert_with(VecDeque::new)
            .push_back(value);
        self
    }

    /// Replaces all values for a header in the response.
    ///
    /// This function replaces all existing values for a header with a single new value.
    ///
    /// # Parameters
    /// - `key`: The header key, which will be converted into a `ResponseHeadersKey`.
    /// - `value`: The value of the header, which will be converted into a String.
    pub fn replace_header<K, V>(&mut self, key: K, value: V) -> &mut Self
    where
        K: Into<ResponseHeadersKey>,
        V: Into<String>,
    {
        let key: ResponseHeadersKey = key.into().to_lowercase();
        if key.trim().is_empty() {
            return self;
        }
        let value: String = value.into();
        let mut deque: VecDeque<String> = VecDeque::new();
        deque.push_back(value);
        self.headers.insert(key, deque);
        self
    }

    /// Removes a header from the response.
    ///
    /// This function removes all values for the specified header key.
    ///
    /// # Parameters
    /// - `key`: The header key to remove, which will be converted into a `ResponseHeadersKey`.
    pub fn remove_header<K>(&mut self, key: K) -> &mut Self
    where
        K: Into<ResponseHeadersKey>,
    {
        let key: ResponseHeadersKey = key.into().to_lowercase();
        let _ = self.headers.remove(&key).is_some();
        self
    }

    /// Removes a specific value from a header in the response.
    ///
    /// This function removes only the specified value from the header.
    /// If the header has multiple values, only the matching value is removed.
    /// If this was the last value for the header, the entire header is removed.
    ///
    /// # Parameters
    /// - `key`: The header key, which will be converted into a `ResponseHeadersKey`.
    /// - `value`: The specific value to remove from the header.
    pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
    where
        K: Into<ResponseHeadersKey>,
        V: Into<String>,
    {
        let key: ResponseHeadersKey = key.into().to_lowercase();
        let value: String = value.into();
        if let Some(values) = self.headers.get_mut(&key) {
            values.retain(|v| v != &value);
            if values.is_empty() {
                self.headers.remove(&key);
            }
        }
        self
    }

    /// Clears all headers from the response.
    ///
    /// This function removes all headers, leaving the headers map empty.
    pub fn clear_headers(&mut self) -> &mut Self {
        self.headers.clear();
        self
    }

    /// Set the body of the response.
    ///
    /// This method allows you to set the body of the response by converting the provided
    /// value into a `ResponseBody` type. The `body` is updated with the converted value,
    /// and the method returns a mutable reference to the current instance for method chaining.
    ///
    /// # Parameters
    /// - `body`: The body of the response to be set. It can be any type that can be converted
    ///   into a `ResponseBody` using the `Into` trait.
    ///
    /// # Return Value
    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
    /// Set the body of the response.
    ///
    /// This method allows you to set the body of the response by converting the provided
    /// value into a `ResponseBody` type. The `body` is updated with the converted value,
    /// and the method returns a mutable reference to the current instance for method chaining.
    ///
    /// # Parameters
    /// - `body`: The body of the response to be set. It can be any type that can be converted
    ///   into a `ResponseBody` using the `Into` trait.
    ///
    /// # Return Value
    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
    pub fn set_body<T>(&mut self, body: T) -> &mut Self
    where
        T: Into<ResponseBody>,
    {
        self.body = body.into();
        self
    }

    /// Set the reason phrase of the response.
    ///
    /// This method allows you to set the reason phrase of the response by converting the
    /// provided value into a `ResponseReasonPhrase` type. The `reason_phrase` is updated
    /// with the converted value, and the method returns a mutable reference to the current
    /// instance for method chaining.
    ///
    /// # Parameters
    /// - `reason_phrase`: The reason phrase to be set for the response. It can be any type
    ///   that can be converted into a `ResponseReasonPhrase` using the `Into` trait.
    ///
    /// # Return Value
    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
    pub fn set_reason_phrase<T>(&mut self, reason_phrase: T) -> &mut Self
    where
        T: Into<ResponseReasonPhrase>,
    {
        self.reason_phrase = reason_phrase.into();
        self
    }

    /// Pushes a header with a key and value into the response string.
    ///
    /// # Parameters
    /// - `response_string`: A mutable reference to the string where the header will be added.
    /// - `key`: The header key as a string slice (`&str`).
    /// - `value`: The header value as a string slice (`&str`).
    fn push_header(response_string: &mut String, key: &str, value: &str) {
        response_string.push_str(key);
        response_string.push_str(COLON_SPACE);
        response_string.push_str(value);
        response_string.push_str(HTTP_BR);
    }

    /// Pushes the first line of an HTTP response (version, status code, and reason phrase) into the response string.
    /// This corresponds to the status line of the HTTP response.
    ///
    /// # Parameters
    /// - `response_string`: A mutable reference to the string where the first line will be added.
    fn push_http_first_line(&self, response_string: &mut String) {
        response_string.push_str(&self.get_version().to_string());
        response_string.push_str(SPACE);
        response_string.push_str(&self.get_status_code().to_string());
        response_string.push_str(SPACE);
        response_string.push_str(self.get_reason_phrase());
        response_string.push_str(HTTP_BR);
    }

    /// Builds the full HTTP response as a byte vector.
    /// # Returns
    /// - `ResponseData`: response data
    pub fn build(&mut self) -> ResponseData {
        if self.reason_phrase.is_empty() {
            self.set_reason_phrase(HttpStatus::phrase(*self.get_status_code()));
        }
        let mut response_string: String = String::new();
        self.push_http_first_line(&mut response_string);
        let mut compress_type_opt: OptionCompress = None;
        let mut connection_opt: OptionString = None;
        let mut content_type_opt: OptionString = None;
        let headers: ResponseHeaders = self
            .get_mut_headers()
            .drain()
            .map(|(key, value)| (key.to_lowercase(), value))
            .collect();
        let mut unset_content_length: bool = false;
        for (key, values) in headers.iter() {
            for value in values.iter() {
                if key == CONTENT_ENCODING {
                    compress_type_opt = Some(value.parse::<Compress>().unwrap_or_default());
                } else if key == CONNECTION {
                    connection_opt = Some(value.to_owned());
                } else if key == CONTENT_TYPE {
                    content_type_opt = Some(value.to_owned());
                    if value.eq_ignore_ascii_case(TEXT_EVENT_STREAM) {
                        unset_content_length = true;
                    }
                }
                Self::push_header(&mut response_string, key, value);
            }
        }
        if connection_opt.is_none() {
            Self::push_header(&mut response_string, CONNECTION, KEEP_ALIVE);
        }
        if content_type_opt.is_none() {
            let mut content_type: String = String::with_capacity(
                TEXT_HTML.len() + SEMICOLON_SPACE.len() + CHARSET_UTF_8.len(),
            );
            content_type.push_str(TEXT_HTML);
            content_type.push_str(SEMICOLON_SPACE);
            content_type.push_str(CHARSET_UTF_8);
            Self::push_header(&mut response_string, CONTENT_TYPE, &content_type);
        }
        let mut body: Cow<Vec<u8>> = Cow::Borrowed(self.get_body());
        if !unset_content_length {
            if let Some(compress_type) = compress_type_opt {
                if !compress_type.is_unknown() {
                    let tmp_body: Cow<'_, Vec<u8>> =
                        compress_type.encode(&body, DEFAULT_BUFFER_SIZE);
                    body = Cow::Owned(tmp_body.into_owned());
                }
            }
            let len_string: String = body.len().to_string();
            Self::push_header(&mut response_string, CONTENT_LENGTH, &len_string);
        }
        response_string.push_str(HTTP_BR);
        let mut response_bytes: Vec<u8> = response_string.into_bytes();
        response_bytes.extend_from_slice(&body);
        response_bytes
    }

    /// Converts the response to a formatted string representation.
    ///
    /// - Returns: A `String` containing formatted response details.
    pub fn get_string(&self) -> String {
        let body: &Vec<u8> = self.get_body();
        let body_type: &'static str = if std::str::from_utf8(body).is_ok() {
            PLAIN
        } else {
            BINARY
        };
        format!(
            "[Response] => [version]: {}; [status code]: {}; [reason]: {}; [headers]: {:?}; [body]: {} bytes {};",
            self.get_version(),
            self.get_status_code(),
            self.get_reason_phrase(),
            self.get_headers(),
            body.len(),
            body_type
        )
    }
}