Skip to content

Commit

Permalink
feat: add deprecation warnings to 0.2 branch in preparation for 0.3
Browse files Browse the repository at this point in the history
  • Loading branch information
jbr committed Apr 7, 2024
1 parent 6f328bd commit 34b7127
Show file tree
Hide file tree
Showing 32 changed files with 139 additions and 91 deletions.
9 changes: 5 additions & 4 deletions api/src/api_conn_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ impl ApiConnExt for Conn {

fn content_type(&self) -> Result<Mime> {
let header_str = self
.headers()
.request_headers()
.get_str(ContentType)
.ok_or(Error::MissingContentType)?;

Expand Down Expand Up @@ -251,7 +251,7 @@ impl ApiConnExt for Conn {
T: Serialize + Sync,
{
let accept = self
.headers()
.request_headers()
.get_str(Accept)
.unwrap_or("*/*")
.split(',')
Expand All @@ -261,14 +261,15 @@ impl ApiConnExt for Conn {
match accept {
Some(AcceptableMime::Json) => {
self.set_body(serde_json::to_string(body)?);
self.headers_mut().insert(ContentType, "application/json");
self.response_headers_mut()
.insert(ContentType, "application/json");
Ok(())
}

#[cfg(feature = "forms")]
Some(AcceptableMime::Form) => {
self.set_body(serde_urlencoded::to_string(body)?);
self.headers_mut()
self.response_headers_mut()
.insert(ContentType, "application/x-www-form-urlencoded");
Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions aws-lambda-example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ fn main() {
|conn: Conn| async move {
let count = conn.session().get::<usize>("count").unwrap_or_default();
let request_id = conn.lambda_context().request_id.clone();
conn.with_header("request-count", count.to_string())
.with_header("request-id", request_id)
conn.with_response_header("request-count", count.to_string())
.with_response_header("request-id", request_id)
.with_session("count", count + 1)
},
Router::new()
Expand Down
6 changes: 3 additions & 3 deletions basic-auth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl Credentials {

// const BASIC: &str = "Basic ";
// pub fn for_conn(conn: &Conn) -> Option<Self> {
// conn.headers()
// conn.request_headers()
// .get_str(KnownHeaderName::Authorization)
// .and_then(|value| {
// if value[..BASIC.len().min(value.len())].eq_ignore_ascii_case(BASIC) {
Expand Down Expand Up @@ -107,12 +107,12 @@ impl BasicAuth {
}

fn is_allowed(&self, conn: &Conn) -> bool {
conn.headers().get_str(Authorization) == Some(&*self.expected_header)
conn.request_headers().get_str(Authorization) == Some(&*self.expected_header)
}

fn deny(&self, conn: Conn) -> Conn {
conn.with_status(Status::Unauthorized)
.with_header(WwwAuthenticate, self.www_authenticate.clone())
.with_response_header(WwwAuthenticate, self.www_authenticate.clone())
.halt()
}
}
Expand Down
4 changes: 2 additions & 2 deletions caching-headers/src/cache_control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ pub enum CacheControlDirective {
#[async_trait]
impl Handler for CacheControlDirective {
async fn run(&self, conn: Conn) -> Conn {
conn.with_header(KnownHeaderName::CacheControl, self.clone())
conn.with_response_header(KnownHeaderName::CacheControl, self.clone())
}
}

#[async_trait]
impl Handler for CacheControlHeader {
async fn run(&self, conn: Conn) -> Conn {
conn.with_header(KnownHeaderName::CacheControl, self.clone())
conn.with_response_header(KnownHeaderName::CacheControl, self.clone())
}
}

Expand Down
42 changes: 31 additions & 11 deletions client/src/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl Conn {
let handler = |conn: trillium::Conn| async move {
let header = conn.headers().get_str("some-request-header").unwrap_or_default();
let header = conn.request_headers().get_str("some-request-header").unwrap_or_default();
let response = format!("some-request-header was {}", header);
conn.ok(response)
};
Expand All @@ -106,7 +106,7 @@ impl Conn {
trillium_testing::with_server(handler, |url| async move {
let mut conn = client.get(url)
.with_header("some-request-header", "header-value") // <--
.with_request_header("some-request-header", "header-value") // <--
.await?;
assert_eq!(
conn.response_body().read_string().await?,
Expand All @@ -117,7 +117,7 @@ impl Conn {
```
*/

pub fn with_header(
pub fn with_request_header(
mut self,
name: impl Into<HeaderName<'static>>,
value: impl Into<HeaderValues>,
Expand All @@ -126,12 +126,22 @@ impl Conn {
self
}

#[deprecated = "use Conn::with_request_header"]
/// see [`with_request_header]
pub fn with_header(
self,
name: impl Into<HeaderName<'static>>,
value: impl Into<HeaderValues>,
) -> Self {
self.with_request_header(name, value)
}

/**
chainable setter for `extending` request headers
```
let handler = |conn: trillium::Conn| async move {
let header = conn.headers().get_str("some-request-header").unwrap_or_default();
let header = conn.request_headers().get_str("some-request-header").unwrap_or_default();
let response = format!("some-request-header was {}", header);
conn.ok(response)
};
Expand All @@ -141,7 +151,7 @@ impl Conn {
trillium_testing::with_server(handler, move |url| async move {
let mut conn = client.get(url)
.with_headers([ // <--
.with_response_headers([ // <--

Check failure on line 154 in client/src/conn.rs

View workflow job for this annotation

GitHub Actions / Build and Test (ubuntu-latest)

no method named `with_response_headers` found for struct `trillium_client::Conn` in the current scope
("some-request-header", "header-value"),
("some-other-req-header", "other-header-value")
])
Expand All @@ -154,8 +164,7 @@ impl Conn {
})
```
*/

pub fn with_headers<HN, HV, I>(mut self, headers: I) -> Self
pub fn with_request_headers<HN, HV, I>(mut self, headers: I) -> Self
where
I: IntoIterator<Item = (HN, HV)> + Send,
HN: Into<HeaderName<'static>>,
Expand All @@ -165,16 +174,27 @@ impl Conn {
self
}

/// see [`with_request_headers`]
#[deprecated = "use Conn::with_request_headers"]
pub fn with_headers<HN, HV, I>(self, headers: I) -> Self
where
I: IntoIterator<Item = (HN, HV)> + Send,
HN: Into<HeaderName<'static>>,
HV: Into<HeaderValues>,
{
self.with_request_headers(headers)
}

/// Chainable method to remove a request header if present
pub fn without_header(mut self, name: impl Into<HeaderName<'static>>) -> Self {
pub fn without_request_header(mut self, name: impl Into<HeaderName<'static>>) -> Self {
self.request_headers.remove(name);
self
}

/**
```
let handler = |conn: trillium::Conn| async move {
conn.with_header("some-header", "some-value")
conn.with_response_header("some-header", "some-value")
.with_status(200)
};
Expand Down Expand Up @@ -206,7 +226,7 @@ impl Conn {
use trillium_client::Client;
let handler = |conn: trillium::Conn| async move {
let header = conn.headers().get_str("some-request-header").unwrap_or_default();
let header = conn.request_headers().get_str("some-request-header").unwrap_or_default();
let response = format!("some-request-header was {}", header);
conn.ok(response)
};
Expand Down Expand Up @@ -312,7 +332,7 @@ impl Conn {

Ok(self
.with_body(serde_json::to_string(body)?)
.with_header(KnownHeaderName::ContentType, "application/json"))
.with_request_header(KnownHeaderName::ContentType, "application/json"))
}

pub(crate) fn response_encoding(&self) -> &'static Encoding {
Expand Down
11 changes: 9 additions & 2 deletions client/tests/default_headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,21 @@ async fn default_headers() -> TestResult {
.with_default_header(UserAgent, "overridden")
.without_default_header(Accept);

let conn = client.get("http://_").without_header(UserAgent).await?;
let conn = client
.get("http://_")
.without_request_header(UserAgent)
.await?;

assert_eq!(
conn.request_headers(),
&Headers::from_iter([(Host, "_"), (Connection, "close")])
);

let conn = client.get("http://_").with_header(Accept, "*/*").await?;
let conn = client
.get("http://_")
.with_request_header(Accept, "*/*")
.await?;

assert_eq!(
conn.request_headers(),
&Headers::from_iter([
Expand Down
4 changes: 2 additions & 2 deletions client/tests/unsafe_headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use trillium_testing::{connector, harness};
async fn bad_characters_in_header_value() {
assert!(Client::new(connector(()))
.get("http://example.com")
.with_header(
.with_request_header(
KnownHeaderName::Referer,
"x\r\nConnection: keep-alive\r\n\r\nGET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
)
Expand All @@ -18,7 +18,7 @@ async fn bad_characters_in_header_value() {
async fn bad_characters_in_header_name() {
assert!(Client::new(connector(()))
.get("http://example.com")
.with_header("dnt: 1\r\nConnection", "keep-alive")
.with_request_header("dnt: 1\r\nConnection", "keep-alive")
.await
.is_err());
}
6 changes: 3 additions & 3 deletions compression/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ fn parse_accept_encoding(header: &str) -> Vec<(CompressionAlgorithm, u8)> {
impl Handler for Compression {
async fn run(&self, mut conn: Conn) -> Conn {
if let Some(header) = conn
.headers()
.request_headers()
.get_str(AcceptEncoding)
.and_then(|h| self.negotiate(h))
{
Expand Down Expand Up @@ -248,12 +248,12 @@ impl Handler for Compression {

if compression_used {
let vary = conn
.headers_mut()
.response_headers()
.get_str(Vary)
.map(|vary| HeaderValues::from(format!("{vary}, Accept-Encoding")))
.unwrap_or_else(|| HeaderValues::from("Accept-Encoding"));

conn.headers_mut().extend([
conn.response_headers_mut().extend([
(ContentEncoding, HeaderValues::from(algo.as_str())),
(Vary, vary),
]);
Expand Down
6 changes: 3 additions & 3 deletions conn-id/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ impl ConnId {
);
// assert that the id is a valid uuid, even if we can't assert a specific value
assert!(Uuid::parse_str(get("/").on(&app).headers_mut().get_str("x-request-id").unwrap()).is_ok());
assert!(Uuid::parse_str(get("/").on(&app).response_headers().get_str("x-request-id").unwrap()).is_ok());
```
*/
pub fn with_id_generator<F>(mut self, id_generator: F) -> Self
Expand Down Expand Up @@ -253,12 +253,12 @@ impl Handler for ConnId {
let id = self
.request_header
.as_ref()
.and_then(|request_header| conn.headers().get_str(request_header.clone()))
.and_then(|request_header| conn.request_headers().get_str(request_header.clone()))
.map(|request_header| Id(request_header.to_string()))
.unwrap_or_else(|| self.generate_id());

if let Some(ref response_header) = self.response_header {
conn.headers_mut()
conn.response_headers_mut()
.insert(response_header.clone(), id.to_string());
}

Expand Down
6 changes: 3 additions & 3 deletions conn-id/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn test_settings() {

let mut conn = get("/").on(&app);

Check warning on line 34 in conn-id/tests/tests.rs

View workflow job for this annotation

GitHub Actions / Build and Test (ubuntu-latest)

variable does not need to be mutable

Check warning on line 34 in conn-id/tests/tests.rs

View workflow job for this annotation

GitHub Actions / Build and Test (macOS-latest)

variable does not need to be mutable

assert!(Uuid::parse_str(conn.headers_mut().get_str("x-something-else").unwrap()).is_ok());
assert!(Uuid::parse_str(conn.response_headers().get_str("x-something-else").unwrap()).is_ok());
assert!(Uuid::parse_str(conn.id()).is_ok());
assert!(Uuid::parse_str(&log_formatter::conn_id(&conn, true)).is_ok());

Expand All @@ -55,12 +55,12 @@ fn test_no_headers() {
);

let mut conn = get("/").on(&app);

Check warning on line 57 in conn-id/tests/tests.rs

View workflow job for this annotation

GitHub Actions / Build and Test (ubuntu-latest)

variable does not need to be mutable

Check warning on line 57 in conn-id/tests/tests.rs

View workflow job for this annotation

GitHub Actions / Build and Test (macOS-latest)

variable does not need to be mutable
assert!(conn.headers_mut().get("x-request-id").is_none());
assert!(conn.response_headers().get("x-request-id").is_none());
assert_eq!(conn.id(), "4fekClhof7");

let mut conn = get("/")

Check warning on line 61 in conn-id/tests/tests.rs

View workflow job for this annotation

GitHub Actions / Build and Test (ubuntu-latest)

variable does not need to be mutable

Check warning on line 61 in conn-id/tests/tests.rs

View workflow job for this annotation

GitHub Actions / Build and Test (macOS-latest)

variable does not need to be mutable
.with_request_header("x-request-id", "ignored")
.on(&app);
assert_eq!(conn.id(), "PAmkU1LPSe");
assert!(conn.headers_mut().get("x-request-id").is_none());
assert!(conn.response_headers().get("x-request-id").is_none());
}
4 changes: 2 additions & 2 deletions cookies/src/cookies_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl Handler for CookiesHandler {
async fn run(&self, mut conn: Conn) -> Conn {
let mut jar: CookieJar = conn.take_state().unwrap_or_default();

if let Some(cookies) = conn.headers().get_values(KnownHeaderName::Cookie) {
if let Some(cookies) = conn.request_headers().get_values(KnownHeaderName::Cookie) {
for cookie in cookies.iter().filter_map(HeaderValue::as_str) {
for pair in cookie.split(';') {
if let Ok(cookie) = Cookie::parse_encoded(String::from(pair)) {
Expand All @@ -40,7 +40,7 @@ impl Handler for CookiesHandler {

async fn before_send(&self, mut conn: Conn) -> Conn {
if let Some(jar) = conn.take_state::<CookieJar>() {
conn.headers_mut().append(
conn.response_headers_mut().append(
KnownHeaderName::SetCookie,
jar.delta()
.map(|cookie| cookie.encoded().to_string())
Expand Down
2 changes: 1 addition & 1 deletion docs/src/overview/conn.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ supports a chainable (fluent) interface for setting properties, like:

```rust,noplaypen
conn.with_status(202)
.with_header("content-type", "application/something-custom")
.with_response_header("content-type", "application/something-custom")
.with_body("this is my custom body")
```

Expand Down
2 changes: 1 addition & 1 deletion example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ struct HelloTemplate<'a> {

async fn request_count(conn: Conn) -> Conn {
let count = conn.session().get::<usize>("count").unwrap_or_default();
conn.with_header("request-count", count.to_string())
conn.with_response_header("request-count", count.to_string())
.with_session("count", count + 1)
}

Expand Down
2 changes: 1 addition & 1 deletion forwarding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ impl Handler for Forwarding {
return conn;
}

let forwarded = match Forwarded::from_headers(conn.headers()) {
let forwarded = match Forwarded::from_headers(conn.request_headers()) {
Ok(Some(forwarded)) => forwarded.into_owned(),
Err(error) => {
log::error!("{error}");
Expand Down
2 changes: 1 addition & 1 deletion head/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl Handler for Head {
.and_then(|body| body.len()),
conn
);
conn.with_header(ContentLength, len.to_string())
conn.with_response_header(ContentLength, len.to_string())
}
}

Expand Down
Loading

0 comments on commit 34b7127

Please sign in to comment.