Skip to main content

Route

Struct Route 

Source
pub struct Route {
    pub path: String,
    pub method: Method,
    pub tsr: bool,
    /* private fields */
}
Expand description

HTTP route with path pattern matching and middleware support.

Fields§

§path: String

Original path string used to create this route.

§method: Method

HTTP method this route responds to.

§tsr: bool

Whether trailing slash redirection is enabled.

Implementations§

Source§

impl Route

Source

pub fn new( path: String, method: Method, handler: BoxHandler, tsr: Option<bool>, ) -> Route

Creates a new route with the specified path, method, and handler.

Source

pub fn middleware<F, Fut, R>(&self, f: F) -> &Route
where F: Fn(Request<TakoBody>, Next) -> Fut + Clone + Send + Sync + 'static, Fut: Future<Output = R> + Send + 'static, R: Responder + Send + 'static,

Adds middleware to this route’s execution chain.

Source

pub fn plugin<P>(&self, plugin: P) -> &Route
where P: TakoPlugin + Clone + Send + Sync + 'static,

Available on crate feature plugins only.

Adds a plugin to this route.

Route-level plugins allow applying functionality like compression, CORS, or rate limiting to specific routes instead of globally. Plugins added to a route are initialized when the route is first accessed.

§Examples
use tako::{router::Router, Method, responder::Responder, types::Request};
use tako::plugins::cors::CorsBuilder;


let mut router = Router::new();
let route = router.route(Method::GET, "/api/data", handler);

// Apply CORS only to this route
let cors = CorsBuilder::new()
    .allow_origin("https://example.com")
    .build();
route.plugin(cors);
Source

pub fn version(&self, version: Version) -> &Route

Restricts this route to a specific HTTP protocol version.

Requests whose version() does not match are answered with 505 HTTP Version Not Supported. Set once at registration; later calls are no-ops (lock-free reads in the hot path).

Source

pub fn h09(&self) -> &Route

HTTP/0.9 guard. Shorthand for Route::version with http::Version::HTTP_09.

Source

pub fn h10(&self) -> &Route

HTTP/1.0 guard. Shorthand for Route::version with http::Version::HTTP_10.

Source

pub fn h11(&self) -> &Route

HTTP/1.1 guard. Shorthand for Route::version with http::Version::HTTP_11.

Source

pub fn h2(&self) -> &Route

HTTP/2 guard. Shorthand for Route::version with http::Version::HTTP_2.

Source

pub fn signals(&self) -> &SignalArbiter

Available on crate feature signals only.

Returns a reference to this route’s signal arbiter.

Source

pub fn signal_arbiter(&self) -> SignalArbiter

Available on crate feature signals only.

Returns a clone of this route’s signal arbiter for shared usage.

Source

pub fn on_signal<F, Fut>(&self, id: impl Into<String>, handler: F)
where F: Fn(Signal) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Available on crate feature signals only.

Registers a handler for a named signal on this route’s arbiter.

Source

pub async fn emit_signal(&self, signal: Signal)

Available on crate feature signals only.

Emits a signal through this route’s arbiter.

Source

pub fn operation_id(&self, id: impl Into<String>) -> &Route

Available on crate features utoipa or vespera only.

Sets a unique operation ID for this route in OpenAPI documentation.

§Examples
router.route(Method::GET, "/users", list_users)
    .operation_id("listUsers");
Source

pub fn summary(&self, summary: impl Into<String>) -> &Route

Available on crate features utoipa or vespera only.

Sets a short summary for this route in OpenAPI documentation.

§Examples
router.route(Method::GET, "/users/{id}", get_user)
    .summary("Get user by ID");
Source

pub fn description(&self, description: impl Into<String>) -> &Route

Available on crate features utoipa or vespera only.

Sets a detailed description for this route in OpenAPI documentation.

§Examples
router.route(Method::GET, "/users/{id}", get_user)
    .description("Retrieves a user by their unique identifier");
Source

pub fn tag(&self, tag: impl Into<String>) -> &Route

Available on crate features utoipa or vespera only.

Adds a tag to group this route in OpenAPI documentation.

§Examples
router.route(Method::GET, "/users", list_users)
    .tag("users")
    .tag("public");
Source

pub fn deprecated(&self) -> &Route

Available on crate features utoipa or vespera only.

Marks this route as deprecated in OpenAPI documentation.

§Examples
router.route(Method::GET, "/v1/users", list_users_v1)
    .deprecated();
Source

pub fn response(&self, status: u16, description: impl Into<String>) -> &Route

Available on crate features utoipa or vespera only.

Adds a response description for a status code in OpenAPI documentation.

§Examples
router.route(Method::GET, "/users/{id}", get_user)
    .response(200, "Successful response with user data")
    .response(404, "User not found");
Source

pub fn parameter(&self, param: OpenApiParameter) -> &Route

Available on crate features utoipa or vespera only.

Adds a parameter definition for this route in OpenAPI documentation.

§Examples
use tako::openapi::{OpenApiParameter, ParameterLocation};

router.route(Method::GET, "/users", list_users)
    .parameter(OpenApiParameter {
        name: "limit".to_string(),
        location: ParameterLocation::Query,
        description: Some("Maximum number of results".to_string()),
        required: false,
    });
Source

pub fn request_body(&self, body: OpenApiRequestBody) -> &Route

Available on crate features utoipa or vespera only.

Sets the request body description for this route in OpenAPI documentation.

§Examples
use tako::openapi::OpenApiRequestBody;

router.route(Method::POST, "/users", create_user)
    .request_body(OpenApiRequestBody {
        description: Some("User data to create".to_string()),
        required: true,
        content_type: "application/json".to_string(),
    });
Source

pub fn security(&self, requirement: impl Into<String>) -> &Route

Available on crate features utoipa or vespera only.

Adds a security requirement for this route in OpenAPI documentation.

§Examples
router.route(Method::DELETE, "/users/{id}", delete_user)
    .security("bearerAuth");
Source

pub fn openapi_metadata(&self) -> Option<RouteOpenApi>

Available on crate features utoipa or vespera only.

Returns a clone of the OpenAPI metadata for this route, if any.

Source

pub fn timeout(&self, duration: Duration) -> &Route

Sets a timeout for this route, overriding the router-level timeout.

When a request exceeds the timeout duration, the timeout fallback handler is invoked (if configured on the router) or a 408 Request Timeout response is returned.

§Examples
use std::time::Duration;

router.route(Method::POST, "/upload", upload_handler)
    .timeout(Duration::from_secs(60));
Source

pub fn simd_json(&self, mode: SimdJsonMode) -> &Route

Configures the SIMD JSON dispatch behavior for this route.

When the simd feature is enabled, Json<T> can use the sonic_rs SIMD parser for faster deserialization. By default, SIMD is used for payloads above 2 MB. This method lets you override that threshold — or force SIMD on/off — for individual routes.

Without the simd feature this setting is accepted but has no effect.

§Examples
use tako::extractors::json::SimdJsonMode;

// Always use SIMD for a heavy ingest endpoint
router.route(Method::POST, "/api/ingest", ingest)
    .simd_json(SimdJsonMode::Always);

// Use SIMD only above 4 KB
router.route(Method::POST, "/api/batch", batch)
    .simd_json(SimdJsonMode::Threshold(4096));

// Disable SIMD for a latency-sensitive tiny-payload route
router.route(Method::POST, "/api/ping", ping)
    .simd_json(SimdJsonMode::Never);

Auto Trait Implementations§

§

impl !Freeze for Route

§

impl !RefUnwindSafe for Route

§

impl Send for Route

§

impl Sync for Route

§

impl Unpin for Route

§

impl UnsafeUnpin for Route

§

impl !UnwindSafe for Route

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> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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