Path

Struct Path 

Source
pub struct Path<'a> { /* private fields */ }
Expand description

A description of a path in the router.

This is generated when you call crate::Router::at, and it contains the passed prefix from that function. Here, you can specify the behavior to perform at that prefix - the Endpoints to perform on each method of that Path.

Paths are specified to have a specific format. At any point in the path, you can use a {} pattern to denote a fragment. These fragments can then be accessed in the endpoint (or any middleware) using crate::Request::fragment. A fragment should have this pattern:

{[name][:<type>]}

Where [name] is the (optional) text-based name for the fragment, and <type> is the (optional) type of the fragment (defaulting to string). There are currently six fragment types:

  • oext: matches an (optional) extension; e.g. .jpeg. This can be used to allow the front-end to optionally specify the expected content-type of the response (in addition to the Accept header).
  • int: matches an integer. This integer can be positive or negative, and has no bound on length; so there is no guarentee it will fit in any native number sizes.
  • uint: matches an unsigned integer. This integer must be positive. It similarly has no bound on length.
  • path: matches anything, including path segments (/). This is similar to the ** glob.
  • uuid: matches an RFC 4122 UUID.
  • none / str / s / string: matches any characters excluding a path segment (/).

Note that using an invalid type will currently cause it to panic. Non-named fragments (e.g. {}) must be indexed using numbers, 1-indexed.

§Examples


let endpoint = || under::endpoints::simple(Response::empty_204); // dummy endpoint
let mut http = under::http(); // this provides us with the Router instance.
http.at("/") // this is the Path instance.
    .get(endpoint());
 // specifies a path that should be a `/users/` followed by any
 // (unsigned) integer, followed by an optional extension (`.json`).
 http.at("/users/{id:uint}{ext:oext}")
    .get(endpoint())
    .post(endpoint());
 // specifies a path that should start with `/public/`, and then
 // some text.  This is required for `dir` to work properly.
 http.at("/public/{:path}")
    .get(endpoint());
 // another example.
 http.at("/actions/{id:uuid}")
    .get(endpoint());
http.prepare();

use http::StatusCode;
eprintln!("{:#?}", http);
expect_response(&http, "/users/1", StatusCode::NO_CONTENT).await?;
expect_response(&http, "/users/1.json", StatusCode::NO_CONTENT).await?;
expect_response(&http, "/users/aaa", StatusCode::INTERNAL_SERVER_ERROR).await?;
expect_response(&http, "/public/aa/a", StatusCode::NO_CONTENT).await?;
expect_response(&http, "/public/", StatusCode::INTERNAL_SERVER_ERROR).await?;
expect_response(&http, "/actions/00000000-0000-0000-0000-000000000000", StatusCode::NO_CONTENT).await?;
expect_response(&http, "/actions/1", StatusCode::INTERNAL_SERVER_ERROR).await?;

Implementations§

Source§

impl<'a> Path<'a>

Source

pub fn at<P: AsRef<str>>(&mut self, path: P) -> Path<'_>

This appends to the prefix, creating a new Path from the current one and the given supplemental prefix. This assumes that the prefix is never terminated with a forward slash, but always prefixed with one.

§Example
let mut base = http.at("/user");
base.get(user_index);
base.at("/{id}")
    .get(user_show)
    .post(user_update)
    .delete(user_destroy);
Source

pub fn under<P: AsRef<str>, F: FnOnce(&mut Path<'_>)>( &mut self, path: P, f: F, ) -> &mut Self

This appends to the prefix, creating a new Path from the current one and the given supplemental prefix. This assumes that the prefix is never terminated with a forward slash, but always prefixed with one.

The created Path is then yielded to the given closure, which can be used to add routes to it; the current Path is then returned.

§Example
http.under("/user", |base| {
    base.get(user_index)
        .under("/{id}", |user| {
            user
                .get(user_show)
                .post(user_update)
                .delete(user_destroy);
        });
});
Source

pub fn all<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates an endpoint responding to any method at the current prefix.

§Examples
let endpoint = under::endpoints::simple(Response::empty_204);
let method = http::Method::from_bytes(b"TEST")?;
http.at("/user").all(endpoint);
http.prepare();
let response = http.handle(Request::from_method("/user", method.clone())?).await?;
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
let response = http.handle(Request::post("/user")?).await?;
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
Source

pub fn method<E: Endpoint>(&mut self, method: Method, endpoint: E) -> &mut Self

Creates an endpoint of the specified method at the current prefix.

§Examples
let method = http::Method::from_bytes(b"TEST")?;
http.at("/user").method(method.clone(), endpoint);
http.prepare();
let response = http.handle(Request::from_method("/user", method)?).await?;
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
Source

pub fn get<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a GET endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").get(endpoint);
http.prepare();
let response = http.handle(under::Request::get("/user")?).await?;
Source

pub fn post<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a POST endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").post(endpoint);
http.prepare();
let response = http.handle(under::Request::post("/user")?).await?;
Source

pub fn options<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a OPTIONS endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").options(endpoint);
http.prepare();
let response = http.handle(under::Request::options("/user")?).await?;
Source

pub fn put<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a PUT endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").put(endpoint);
http.prepare();
let response = http.handle(under::Request::put("/user")?).await?;
Source

pub fn delete<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a DELETE endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").delete(endpoint);
http.prepare();
let response = http.handle(under::Request::delete("/user")?).await?;
Source

pub fn head<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a HEAD endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").head(endpoint);
http.prepare();
let response = http.handle(under::Request::head("/user")?).await?;
Source

pub fn trace<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a TRACE endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").trace(endpoint);
http.prepare();
let response = http.handle(under::Request::trace("/user")?).await?;
Source

pub fn connect<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a CONNECT endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").connect(endpoint);
http.prepare();
let response = http.handle(under::Request::connect("/user")?).await?;
Source

pub fn patch<E: Endpoint>(&mut self, endpoint: E) -> &mut Self

Creates a PATCH endpoint at the current prefix.

§Examples
let mut http = under::http();
let endpoint = under::endpoints::simple(under::Response::empty_204);
http.at("/user").patch(endpoint);
http.prepare();
let response = http.handle(under::Request::patch("/user")?).await?;

Trait Implementations§

Source§

impl<'a> Debug for Path<'a>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Path<'a>

§

impl<'a> !RefUnwindSafe for Path<'a>

§

impl<'a> Send for Path<'a>

§

impl<'a> Sync for Path<'a>

§

impl<'a> Unpin for Path<'a>

§

impl<'a> !UnwindSafe for Path<'a>

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> 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, U> TryFrom<U> for T
where U: Into<T>,

Source§

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>,

Source§

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
Source§

impl<T> ErasedDestructor for T
where T: 'static,