pub struct Host(pub String);Expand description
Host extractor
从 HTTP 请求中提取 Host 信息,兼容 HTTP/1.x 和 HTTP/2
§工作原理
- HTTP/1.x: 从
Hostheader 中读取 - HTTP/2: 优先从
:authoritypseudo-header 读取,回退到Hostheader
§示例
use axum::{Router, routing::get};
use axum_bootstrap::util::extractor::Host;
async fn show_host(Host(host): Host) -> String {
format!("Your host is: {}", host)
}
let app = Router::new().route("/", get(show_host));§错误处理
如果请求中没有 Host 信息,将返回 500 错误
§可选 Host 提取
如果你希望 Host 是可选的(不存在时不报错),可以使用 Option<Host>:
use axum::{Router, routing::get};
use axum_bootstrap::util::extractor::Host;
async fn show_host(host: Option<Host>) -> String {
match host {
Some(Host(h)) => format!("Your host is: {}", h),
None => "No host provided".to_string(),
}
}
let app = Router::new().route("/", get(show_host));Tuple Fields§
§0: StringTrait Implementations§
Auto Trait Implementations§
impl Freeze for Host
impl RefUnwindSafe for Host
impl Send for Host
impl Sync for Host
impl Unpin for Host
impl UnsafeUnpin for Host
impl UnwindSafe for Host
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<S, T> FromRequest<S, ViaParts> for T
impl<S, T> FromRequest<S, ViaParts> for T
Source§type Rejection = <T as FromRequestParts<S>>::Rejection
type Rejection = <T as FromRequestParts<S>>::Rejection
If the extractor fails it’ll use this “rejection” type. A rejection is
a kind of error that can be converted into a response.
Source§fn from_request(
req: Request<Body>,
state: &S,
) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>
fn from_request( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>
Perform the extraction.