Struct axum::extract::OriginalUri

source ·
pub struct OriginalUri(pub Uri);
Expand description

Extractor that gets the original request URI regardless of nesting.

This is necessary since Uri, when used as an extractor, will have the prefix stripped if used in a nested service.

§Example

use axum::{
    routing::get,
    Router,
    extract::OriginalUri,
    http::Uri
};

let api_routes = Router::new()
    .route(
        "/users",
        get(|uri: Uri, OriginalUri(original_uri): OriginalUri| async {
            // `uri` is `/users`
            // `original_uri` is `/api/users`
        }),
    );

let app = Router::new().nest("/api", api_routes);

§Extracting via request extensions

OriginalUri can also be accessed from middleware via request extensions. This is useful for example with Trace to create a span that contains the full path, if your service might be nested:

use axum::{
    Router,
    extract::OriginalUri,
    http::Request,
    routing::get,
};
use tower_http::trace::TraceLayer;

let api_routes = Router::new()
    .route("/users/:id", get(|| async { /* ... */ }))
    .layer(
        TraceLayer::new_for_http().make_span_with(|req: &Request<_>| {
            let path = if let Some(path) = req.extensions().get::<OriginalUri>() {
                // This will include `/api`
                path.0.path().to_owned()
            } else {
                // The `OriginalUri` extension will always be present if using
                // `Router` unless another extractor or middleware has removed it
                req.uri().path().to_owned()
            };
            tracing::info_span!("http-request", %path)
        }),
    );

let app = Router::new().nest("/api", api_routes);

Tuple Fields§

§0: Uri

Methods from Deref<Target = Uri>§

source

pub fn path_and_query(&self) -> Option<&PathAndQuery>

Returns the path & query components of the Uri

source

pub fn path(&self) -> &str

Get the path of this Uri.

Both relative and absolute URIs contain a path component, though it might be the empty string. The path component is case sensitive.

abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1
                                       |--------|
                                            |
                                          path

If the URI is * then the path component is equal to *.

§Examples

A relative URI


let uri: Uri = "/hello/world".parse().unwrap();

assert_eq!(uri.path(), "/hello/world");

An absolute URI

let uri: Uri = "http://example.org/hello/world".parse().unwrap();

assert_eq!(uri.path(), "/hello/world");
source

pub fn scheme(&self) -> Option<&Scheme>

Get the scheme of this Uri.

The URI scheme refers to a specification for assigning identifiers within that scheme. Only absolute URIs contain a scheme component, but not all absolute URIs will contain a scheme component. Although scheme names are case-insensitive, the canonical form is lowercase.

abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1
|-|
 |
scheme
§Examples

Absolute URI

use http::uri::{Scheme, Uri};

let uri: Uri = "http://example.org/hello/world".parse().unwrap();

assert_eq!(uri.scheme(), Some(&Scheme::HTTP));

Relative URI

let uri: Uri = "/hello/world".parse().unwrap();

assert!(uri.scheme().is_none());
source

pub fn scheme_str(&self) -> Option<&str>

Get the scheme of this Uri as a &str.

§Example
let uri: Uri = "http://example.org/hello/world".parse().unwrap();

assert_eq!(uri.scheme_str(), Some("http"));
source

pub fn authority(&self) -> Option<&Authority>

Get the authority of this Uri.

The authority is a hierarchical element for naming authority such that the remainder of the URI is delegated to that authority. For HTTP, the authority consists of the host and port. The host portion of the authority is case-insensitive.

The authority also includes a username:password component, however the use of this is deprecated and should be avoided.

abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1
      |-------------------------------|
                    |
                authority
§Examples

Absolute URI

let uri: Uri = "http://example.org:80/hello/world".parse().unwrap();

assert_eq!(uri.authority().map(|a| a.as_str()), Some("example.org:80"));

Relative URI

let uri: Uri = "/hello/world".parse().unwrap();

assert!(uri.authority().is_none());
source

pub fn host(&self) -> Option<&str>

Get the host of this Uri.

The host subcomponent of authority is identified by an IP literal encapsulated within square brackets, an IPv4 address in dotted- decimal form, or a registered name. The host subcomponent is case-insensitive.

abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1
                        |---------|
                             |
                            host
§Examples

Absolute URI

let uri: Uri = "http://example.org:80/hello/world".parse().unwrap();

assert_eq!(uri.host(), Some("example.org"));

Relative URI

let uri: Uri = "/hello/world".parse().unwrap();

assert!(uri.host().is_none());
source

pub fn port(&self) -> Option<Port<&str>>

Get the port part of this Uri.

The port subcomponent of authority is designated by an optional port number following the host and delimited from it by a single colon (“:”) character. It can be turned into a decimal port number with the as_u16 method or as a str with the as_str method.

abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1
                                    |-|
                                     |
                                    port
§Examples

Absolute URI with port

let uri: Uri = "http://example.org:80/hello/world".parse().unwrap();

let port = uri.port().unwrap();
assert_eq!(port.as_u16(), 80);

Absolute URI without port

let uri: Uri = "http://example.org/hello/world".parse().unwrap();

assert!(uri.port().is_none());

Relative URI

let uri: Uri = "/hello/world".parse().unwrap();

assert!(uri.port().is_none());
source

pub fn port_u16(&self) -> Option<u16>

Get the port of this Uri as a u16.

§Example
let uri: Uri = "http://example.org:80/hello/world".parse().unwrap();

assert_eq!(uri.port_u16(), Some(80));
source

pub fn query(&self) -> Option<&str>

Get the query string of this Uri, starting after the ?.

The query component contains non-hierarchical data that, along with data in the path component, serves to identify a resource within the scope of the URI’s scheme and naming authority (if any). The query component is indicated by the first question mark (“?”) character and terminated by a number sign (“#”) character or by the end of the URI.

abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1
                                                  |-------------------|
                                                            |
                                                          query
§Examples

Absolute URI

let uri: Uri = "http://example.org/hello/world?key=value".parse().unwrap();

assert_eq!(uri.query(), Some("key=value"));

Relative URI with a query string component

let uri: Uri = "/hello/world?key=value&foo=bar".parse().unwrap();

assert_eq!(uri.query(), Some("key=value&foo=bar"));

Relative URI without a query string component

let uri: Uri = "/hello/world".parse().unwrap();

assert!(uri.query().is_none());

Trait Implementations§

source§

impl Clone for OriginalUri

source§

fn clone(&self) -> OriginalUri

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for OriginalUri

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Deref for OriginalUri

§

type Target = Uri

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl DerefMut for OriginalUri

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl<S> FromRequestParts<S> for OriginalUri
where S: Send + Sync,

§

type Rejection = Infallible

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_parts<'life0, 'life1, 'async_trait>( parts: &'life0 mut Parts, state: &'life1 S ) -> Pin<Box<dyn Future<Output = Result<Self, Self::Rejection>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Perform the extraction.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FromRef<T> for T
where T: Clone,

source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
source§

impl<S, B, T> FromRequest<S, B, ViaParts> for T
where B: Send + 'static, S: Send + Sync, T: FromRequestParts<S>,

§

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<'life0, 'async_trait>( req: Request<B>, state: &'life0 S ) -> Pin<Box<dyn Future<Output = Result<T, <T as FromRequest<S, B, ViaParts>>::Rejection>> + Send + 'async_trait>>
where 'life0: 'async_trait, T: 'async_trait,

Perform the extraction.
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more