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.
Replies: 2 comments 6 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.
-
Scheme not available on the uri. How to define it? |
Beta Was this translation helpful? Give feedback.
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.