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 pub fn new() -> Self {
29 Self::default()
30 }
31}
32
33impl Config {
34 /// Adds a header to be added to every request by this config.
35 ///
36 /// Default: No extra headers.
37 pub fn add_header(
38 mut self,
39 name: impl Into<HeaderName>,
40 values: impl ToHeaderValues,
41 ) -> Result<Self> {
42 self.headers
43 .insert(name.into(), values.to_header_values()?.collect());
44 Ok(self)
45 }
46
47 /// Sets the base URL for this config. All request URLs will be relative to this URL.
48 ///
49 /// Note: a trailing slash is significant.
50 /// Without it, the last path component is considered to be a “file” name
51 /// to be removed to get at the “directory” that is used as the base.
52 ///
53 /// Default: `None` (internally).
54 pub fn set_base_url(mut self, base: Url) -> Self {
55 self.base_url = Some(base);
56 self
57 }
58}