Accessing the full URI in middleware #1149
-
I'm trying to write a middleware that redirects from HTTP -> HTTPS, and to do that, I need to be able to access the full URI in the middleware. I saw in #858 that this might be possible by extracting /// Redirect HTTP requests to HTTPS
pub struct HTTPSRedirectLayer {
enabled: bool,
}
impl HTTPSRedirectLayer {
pub fn new(enabled: bool) -> Self {
Self { enabled }
}
}
impl<S> Layer<S> for HTTPSRedirectLayer {
type Service = HTTPSRedirectMiddleware<S>;
fn layer(&self, inner: S) -> Self::Service {
HTTPSRedirectMiddleware {
enabled: self.enabled,
inner,
}
}
}
#[derive(Clone)]
pub struct HTTPSRedirectMiddleware<S> {
enabled: bool,
inner: S,
}
impl<S> Service<Request<Body>> for HTTPSRedirectMiddleware<S>
where
S: Service<Request<Body>, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let uri = req.extensions().get::<Uri>().unwrap();
dbg!(self.enabled, &uri, &req);
let future = self.inner.call(req);
Box::pin(async move {
let response: Response = future.await?;
Ok(response)
})
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Jul 10, 2022
Replies: 1 comment 5 replies
-
The uri is available directly in the request https://docs.rs/http/0.2.8/http/request/struct.Request.html#method.uri. No extensions needed. |
Beta Was this translation helpful? Give feedback.
5 replies
Answer selected by
rouge8
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The uri is available directly in the request https://docs.rs/http/0.2.8/http/request/struct.Request.html#method.uri. No extensions needed.