Skip to main content

Router

Struct Router 

Source
pub struct Router { /* private fields */ }
Expand description

Maps HTTP method + path pairs to handler functions.

Routes are inserted into a trie during registration, then frozen via freeze() before serving. Static segments take priority over parameterized segments (:name) during matching.

Implementations§

Source§

impl Router

Source

pub fn new() -> Self

Create an empty router with default buffer settings.

Source

pub fn max_request_body(self, bytes: usize) -> Self

Set the maximum request body size in bytes (capped at 256 MB).

Source

pub fn sse_buffer_size(self, size: usize) -> Self

Set the channel buffer size for SSE connections.

Controls how many events can be queued before backpressure applies. Default: 32.

Source

pub fn ws_buffer_size(self, size: usize) -> Self

Set the channel buffer size for WebSocket connections.

Controls how many messages can be queued in each direction before backpressure applies. Default: 32.

Source

pub fn skip_middleware_for_internal(self, skip: bool) -> Self

Skip middleware for internal routes (/health, /metrics, /debug/pprof/cpu).

Default: false (middleware applies to all routes including internal ones). Set to true to restore the pre-v3 behavior where internal routes bypass middleware, useful when health probes (Kubernetes, load balancers) cannot send auth headers.

Source

pub fn use_middleware<F, Fut>(&mut self, mw: F)
where F: Fn(&Request, Next<'_>) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Register async middleware that wraps all route handlers.

Middleware registered first executes outermost (wraps all later middleware). Each middleware receives the request and a Next handle — call next.call(req).await to continue the chain.

router.use_middleware(|req, next| async move {
    let resp = next.call(req).await;
    resp.with_header("X-Custom", "value")
});
Source

pub fn get<F, Fut, R>(&mut self, path: &str, handler: F)
where F: Fn(&Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = R> + Send + 'static, R: IntoResponse + 'static,

Register a GET handler for path.

Path segments beginning with : are captured as named parameters.

Source

pub fn post<F, Fut, R>(&mut self, path: &str, handler: F)
where F: Fn(&Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = R> + Send + 'static, R: IntoResponse + 'static,

Register a POST handler for path.

Source

pub fn put<F, Fut, R>(&mut self, path: &str, handler: F)
where F: Fn(&Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = R> + Send + 'static, R: IntoResponse + 'static,

Register a PUT handler for path.

Source

pub fn delete<F, Fut, R>(&mut self, path: &str, handler: F)
where F: Fn(&Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = R> + Send + 'static, R: IntoResponse + 'static,

Register a DELETE handler for path.

Source

pub fn patch<F, Fut, R>(&mut self, path: &str, handler: F)
where F: Fn(&Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = R> + Send + 'static, R: IntoResponse + 'static,

Register a PATCH handler for path.

Source

pub fn head<F, Fut, R>(&mut self, path: &str, handler: F)
where F: Fn(&Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = R> + Send + 'static, R: IntoResponse + 'static,

Register a HEAD handler for path.

If you do not register one, Camber can still answer HEAD requests for matching GET routes by stripping the response body automatically.

Source

pub fn options<F, Fut, R>(&mut self, path: &str, handler: F)
where F: Fn(&Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = R> + Send + 'static, R: IntoResponse + 'static,

Register an OPTIONS handler for path.

Source

pub fn get_stream( &mut self, path: &str, handler: impl Fn(&Request) -> Pin<Box<dyn Future<Output = StreamResponse> + Send>> + Send + Sync + 'static, )

Register an async streaming handler for GET requests.

The handler returns a StreamResponse for incremental body delivery. Use StreamResponse::new() to get both the response and a sender.

Source

pub fn post_stream( &mut self, path: &str, handler: impl Fn(&Request) -> Pin<Box<dyn Future<Output = StreamResponse> + Send>> + Send + Sync + 'static, )

Register an async streaming handler for POST requests.

Source

pub fn get_sse( &mut self, path: &str, handler: impl Fn(&Request, &mut SseWriter) -> Result<(), RuntimeError> + Send + Sync + 'static, )

Register an SSE streaming handler for GET requests.

The handler receives the request and an SseWriter for sending events. The connection stays open until the handler returns or the client disconnects.

Source

pub fn ws( &mut self, path: &str, handler: impl Fn(&Request, WsConn) -> Result<(), RuntimeError> + Send + Sync + 'static, )

Register a WebSocket handler for the given path.

The handler receives the upgrade request and a bidirectional WsConn. The connection stays open until the handler returns or the client disconnects.

Source

pub fn grpc(&mut self, grpc_router: GrpcRouter)

Register a gRPC service (generated by camber-build).

Requests with content-type: application/grpc are forwarded to the tonic service. All other requests go through normal HTTP routing.

Source

pub fn proxy(&mut self, prefix: &str, backend: &str)

Register a reverse proxy that forwards requests under prefix to backend.

The prefix is stripped from the request path before forwarding. All HTTP methods are handled. The full upstream response is buffered, so middleware can inspect and modify the response body. On backend failure, returns 502.

Source

pub fn proxy_checked( &mut self, prefix: &str, backend: &str, healthy: Arc<AtomicBool>, )

Register a health-checked reverse proxy.

Behaves like proxy() but checks the healthy flag before forwarding. When healthy is false, returns 503 immediately.

Source

pub fn proxy_stream(&mut self, prefix: &str, backend: &str)

Register a streaming reverse proxy under prefix.

Like proxy(), but the upstream response body is forwarded chunk-by-chunk with backpressure instead of being buffered in memory. Middleware acts as a request gate only — it can reject before the upstream call, but does not wrap the streamed response.

Source

pub fn proxy_checked_stream( &mut self, prefix: &str, backend: &str, healthy: Arc<AtomicBool>, )

Register a health-checked streaming reverse proxy.

Behaves like proxy_stream() but checks the healthy flag before forwarding. When healthy is false, returns 503 immediately.

Source

pub fn static_files(&mut self, prefix: &str, dir: &str)

Serve static files from dir under the given URL prefix.

Trait Implementations§

Source§

impl Debug for Router

Source§

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

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

impl Default for Router

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

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<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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