diff --git a/src/agent.rs b/src/agent.rs index 5c018cc..a2e1bf1 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -36,6 +36,7 @@ pub(crate) struct AgentConfig { pub timeout_write: Option, pub timeout: Option, pub redirects: u32, + pub user_agent: String, #[cfg(feature = "tls")] pub tls_config: Option, } @@ -208,6 +209,7 @@ impl AgentBuilder { timeout_write: None, timeout: None, redirects: 5, + user_agent: format!("ureq/{}", env!("CARGO_PKG_VERSION")), #[cfg(feature = "tls")] tls_config: None, }, @@ -434,6 +436,39 @@ impl AgentBuilder { self } + /// The user-agent header to associate with all requests from this agent by default. + /// + /// Defaults to `ureq/[VERSION]`. You can override the user-agent on an individual request by + /// setting the `User-Agent` header when constructing the request. + /// + /// ``` + /// # #[cfg(feature = "json")] + /// # fn main() -> Result<(), ureq::Error> { + /// # ureq::is_test(true); + /// let agent = ureq::builder() + /// .user_agent("ferris/1.0") + /// .build(); + /// + /// // Uses agent's header + /// let result: serde_json::Value = + /// agent.get("http://httpbin.org/headers").call()?.into_json()?; + /// assert_eq!(&result["headers"]["User-Agent"], "ferris/1.0"); + /// + /// // Overrides user-agent set on the agent + /// let result: serde_json::Value = agent.get("http://httpbin.org/headers") + /// .set("User-Agent", "super-ferris/2.0") + /// .call()?.into_json()?; + /// assert_eq!(&result["headers"]["User-Agent"], "super-ferris/2.0"); + /// # Ok(()) + /// # } + /// # #[cfg(not(feature = "json"))] + /// # fn main() {} + /// ``` + pub fn user_agent(mut self, user_agent: &str) -> Self { + self.config.user_agent = user_agent.into(); + self + } + /// Set the TLS client config to use for the connection. See [`ClientConfig`](https://docs.rs/rustls/latest/rustls/struct.ClientConfig.html). /// /// Example: diff --git a/src/unit.rs b/src/unit.rs index 1ba0686..2c6be0a 100644 --- a/src/unit.rs +++ b/src/unit.rs @@ -342,8 +342,6 @@ fn connect_socket(unit: &Unit, hostname: &str, use_pooled: bool) -> Result<(Stre /// Send request line + headers (all up until the body). #[allow(clippy::write_with_newline)] fn send_prelude(unit: &Unit, stream: &mut Stream, redir: bool) -> io::Result<()> { - // - // build into a buffer and send in one go. let mut prelude: Vec = vec![]; @@ -379,11 +377,7 @@ fn send_prelude(unit: &Unit, stream: &mut Stream, redir: bool) -> io::Result<()> } } if !header::has_header(&unit.headers, "user-agent") { - write!( - prelude, - "User-Agent: ureq/{}\r\n", - env!("CARGO_PKG_VERSION") - )?; + write!(prelude, "User-Agent: {}\r\n", &unit.agent.config.user_agent)?; } if !header::has_header(&unit.headers, "accept") { write!(prelude, "Accept: */*\r\n")?;