|
| 1 | +extern crate futures; |
| 2 | +extern crate http; |
| 3 | +extern crate tower; |
| 4 | + |
| 5 | +use futures::Poll; |
| 6 | +use http::Request; |
| 7 | +use http::uri::{Authority, Scheme}; |
| 8 | +use tower::Service; |
| 9 | + |
| 10 | +/// Wraps an HTTP service, injecting authority and scheme on every request. |
| 11 | +pub struct AddOrigin<T> { |
| 12 | + inner: T, |
| 13 | + scheme: Scheme, |
| 14 | + authority: Authority, |
| 15 | +} |
| 16 | + |
| 17 | +impl<T> AddOrigin<T> { |
| 18 | + /// Create a new `AddOrigin` |
| 19 | + pub fn new(inner: T, scheme: Scheme, authority: Authority) -> Self { |
| 20 | + AddOrigin { |
| 21 | + inner, |
| 22 | + authority, |
| 23 | + scheme, |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + /// Return a reference to the HTTP scheme that is added to all requests. |
| 28 | + pub fn scheme(&self) -> &Scheme { |
| 29 | + &self.scheme |
| 30 | + } |
| 31 | + |
| 32 | + /// Return a reference to the HTTP authority that is added to all requests. |
| 33 | + pub fn authority(&self) -> &Authority { |
| 34 | + &self.authority |
| 35 | + } |
| 36 | + |
| 37 | + /// Returns a reference to the inner service. |
| 38 | + pub fn get_ref(&self) -> &T { |
| 39 | + &self.inner |
| 40 | + } |
| 41 | + |
| 42 | + /// Returns a mutable reference to the inner service. |
| 43 | + pub fn get_mut(&mut self) -> &mut T { |
| 44 | + &mut self.inner |
| 45 | + } |
| 46 | + |
| 47 | + /// Consumes `self`, returning the inner service. |
| 48 | + pub fn into_inner(self) -> T { |
| 49 | + self.inner |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl<T, B> Service for AddOrigin<T> |
| 54 | +where T: Service<Request = Request<B>>, |
| 55 | +{ |
| 56 | + type Request = Request<B>; |
| 57 | + type Response = T::Response; |
| 58 | + type Error = T::Error; |
| 59 | + type Future = T::Future; |
| 60 | + |
| 61 | + fn poll_ready(&mut self) -> Poll<(), Self::Error> { |
| 62 | + self.inner.poll_ready() |
| 63 | + } |
| 64 | + |
| 65 | + fn call(&mut self, req: Self::Request) -> Self::Future { |
| 66 | + // Split the request into the head and the body. |
| 67 | + let (mut head, body) = req.into_parts(); |
| 68 | + |
| 69 | + // Split the request URI into parts. |
| 70 | + let mut uri: http::uri::Parts = head.uri.into(); |
| 71 | + |
| 72 | + // Update the URI parts, setting hte scheme and authority |
| 73 | + uri.scheme = Some(self.scheme.clone()); |
| 74 | + uri.authority = Some(self.authority.clone()); |
| 75 | + |
| 76 | + // Update the the request URI |
| 77 | + head.uri = http::Uri::from_parts(uri) |
| 78 | + .expect("valid uri"); |
| 79 | + |
| 80 | + let request = Request::from_parts(head, body); |
| 81 | + |
| 82 | + // Call the inner service |
| 83 | + self.inner.call(request) |
| 84 | + } |
| 85 | +} |
0 commit comments