Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Host extractor #827

Merged
merged 7 commits into from
Mar 6, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
59 changes: 59 additions & 0 deletions axum/src/extract/host.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use super::{FromRequest, RequestParts};
use async_trait::async_trait;
use std::{convert::Infallible};

/// Extractor that extracts the host from a request.
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
#[derive(Debug, Clone, Default)]
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
pub struct Host(pub String);

#[async_trait]
impl<B> FromRequest<B> for Host
where
B: Send,
{
type Rejection = Infallible;

async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
if let Some(host) = req.uri().host() {
return Ok(Host(host.to_string()));
jplatte marked this conversation as resolved.
Show resolved Hide resolved
}

if let Some(Ok(host)) = req.headers().get("host").map(|host| host.to_str()) {
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
return Ok(Host(host.to_string()));
}
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved

Ok(Host("".to_string()))
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::extract::RequestParts;
use http::Request;

#[tokio::test]
async fn test_host() {
let mut req = RequestParts::new(
Request::builder()
.uri("http://example.com/test")
.body(())
.unwrap(),
);
assert_eq!(
&Host::from_request(&mut req).await.unwrap().0,
"example.com"
);

let mut req = RequestParts::new(
Request::builder()
.header("host", "cats.fun")
.body(())
.unwrap(),
);
assert_eq!(
&Host::from_request(&mut req).await.unwrap().0,
"cats.fun"
);
}
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
}
2 changes: 2 additions & 0 deletions axum/src/extract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ pub use self::{
request_parts::{BodyStream, RawBody},
};

pub mod host;
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved

#[doc(no_inline)]
#[cfg(feature = "json")]
pub use crate::Json;
Expand Down