Skip to content
Myr

fix(axum-extra): handle missing optional typed headers (#3886)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by cui fliter · committed by GitHub · parent 8aae593 · Browse files · 1 file+28 added−3 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: cuishuang <imcusg@gmail.com>

Diff stats

1 file+28 added−3 removed

  • other:+28 added−3 removed

1 file+28 added−3 removed

modified:axum-extra/src/typed_header.rs+28 added-3 removed
88 unmodified lines
89 parts: &mut Parts,90 _state: &S,91 ) -> Result<Option<Self>, Self::Rejection> {92 let mut values = parts.headers.get_all(T::name()).iter();93 let is_missing = values.size_hint() == (0, Some(0));93 if values.size_hint() == (0, Some(0)) {94 return Ok(None);95 }9697 match T::decode(&mut values) {95 Ok(res) => Ok(Some(Self(res))),96 Err(_) if is_missing => Ok(None),98 Ok(value) => Ok(Some(Self(value))),99 Err(err) => Err(TypedHeaderRejection {100 name: T::name(),101 reason: TypedHeaderRejectionReason::Error(err),102 }),
112 unmodified lines
215mod tests {216 use super::*;217 use crate::test_helpers::*;218 use axum::{routing::get, Router};219 use http::StatusCode;220221 #[tokio::test]222 async fn typed_header() {223 async fn handle(
28 unmodified lines
252 let res = client.get("/").header("cookie", "a=1").await;253 let body = res.text().await;254 assert_eq!(body, "Header of type `user-agent` was missing");255 }256257 #[tokio::test]258 async fn optional_cookie_is_none_when_missing() {259 async fn handle(cookie: Option<TypedHeader<headers::Cookie>>) -> &'static str {260 if cookie.is_none() {261 "none"262 } else {263 "some"264 }265 }266267 let app = Router::new().route("/", get(handle));268 let client = TestClient::new(app);269270 let res = client.get("/").await;271 assert_eq!(res.status(), StatusCode::OK);272 assert_eq!(res.text().await, "none");273274 let res = client.get("/").header("cookie", "a=1").await;275 assert_eq!(res.status(), StatusCode::OK);276 assert_eq!(res.text().await, "some");277 }278}