Struct aitch::middlewares::SimpleRouter[][src]

pub struct SimpleRouter { /* fields omitted */ }

A simple request router, which determines which handler to call based on the request URI's path.

This is a simple request router, inspired by Go's net/http ServeMux.

It matches the path component of a HTTP request's URI against a collection of registered path prefixes, and calls the handler whose path prefix most closely matches. (e.g. if both /path/a and /path/ab are registered, a request for /path/abc/ will call the latter).

This router is intended primarily to serve as an example of writing complex middleware using aitch, and library users are encouraged to read its source code.

The router is not intended for production applications, and lacks many features that are present in the routers of other web frameworks/toolkits.

Example

extern crate aitch;
extern crate http;

use aitch::servers::hyper::Server;
use aitch::{middlewares, Responder, ResponseBuilder, Result};
use http::Request;

fn handler1(_req: Request<()>, mut resp: ResponseBuilder) -> impl Responder {
    resp.body("Handler 1!".to_owned())
}

fn handler2(_req: Request<()>, mut resp: ResponseBuilder) -> impl Responder {
    resp.body("Handler 2!".to_owned())
}

fn main() -> Result<()> {
    let mut router = middlewares::SimpleRouter::new();
    router.register_handler("/", handler1);
    router.register_handler("/handler2", handler2);

    let handler = middlewares::with_stdout_logging(router);

    let addr = "127.0.0.1:3000".parse()?;
    println!("Listening on http://{}", addr);
    Server::new(addr, handler)?.run()
}

Methods

impl SimpleRouter
[src]

Creates a new SimpleRouter, with no routes registered.

Registers a handler with the given pattern.

This method registers a new handler with the router, using the provided pattern.

See the module level documentation for more details on how patterns are matched.

Panics

This method panics if a handler is already registered with the provided pattern.

Returns the handler to be used for a request with the given URI.

Returns None if no handler matches the URI.

Trait Implementations

impl Default for SimpleRouter
[src]

Returns the "default value" for a type. Read more

impl Handler<BodyStream> for SimpleRouter
[src]

The Responder type returned by this Handler.

Handles an incoming HTTP request, returning a Responder describing a HTTP response.

Auto Trait Implementations