crux_http/
config.rs

1//! Configuration for `HttpClient`s.
2
3use std::{collections::HashMap, fmt::Debug};
4
5use http_types::{
6    headers::{HeaderName, HeaderValues, ToHeaderValues},
7    Url,
8};
9
10use crate::Result;
11
12/// Configuration for `crux_http::Http`s and their underlying HTTP client.
13#[non_exhaustive]
14#[derive(Clone, Debug, Default)]
15pub struct Config {
16    /// The base URL for a client. All request URLs will be relative to this URL.
17    ///
18    /// Note: a trailing slash is significant.
19    /// Without it, the last path component is considered to be a “file” name
20    /// to be removed to get at the “directory” that is used as the base.
21    pub base_url: Option<Url>,
22    /// Headers to be applied to every request made by this client.
23    pub headers: HashMap<HeaderName, HeaderValues>,
24}
25
26impl Config {
27    /// Construct new empty config.
28    #[must_use]
29    pub fn new() -> Self {
30        Self::default()
31    }
32}
33
34impl Config {
35    /// Adds a header to be added to every request by this config.
36    ///
37    /// Default: No extra headers.
38    ///
39    /// # Errors
40    /// Returns an error if the header values are invalid.
41    #[allow(clippy::needless_pass_by_value)] // TODO: revisit this when we are ready to make a breaking API change
42    pub fn add_header(
43        mut self,
44        name: impl Into<HeaderName>,
45        values: impl ToHeaderValues,
46    ) -> Result<Self> {
47        self.headers
48            .insert(name.into(), values.to_header_values()?.collect());
49        Ok(self)
50    }
51
52    /// Sets the base URL for this config. All request URLs will be relative to this URL.
53    ///
54    /// Note: a trailing slash is significant.
55    /// Without it, the last path component is considered to be a “file” name
56    /// to be removed to get at the “directory” that is used as the base.
57    ///
58    /// Default: `None` (internally).
59    #[must_use]
60    pub fn set_base_url(mut self, base: Url) -> Self {
61        self.base_url = Some(base);
62        self
63    }
64}