[][src]Struct tide::App

pub struct App<State> { /* fields omitted */ }

The entry point for building a Tide application.

Apps are built up as a combination of state, endpoints and middleware:

  • Application state is user-defined, and is provided via the App::new function. The state is available as a shared reference to all app endpoints.

  • Endpoints provide the actual application-level code corresponding to particular URLs. The App::at method creates a new route (using standard router syntax), which can then be used to register endpoints for particular HTTP request types.

  • Middleware extends the base Tide framework with additional request or response processing, such as compression, default headers, or logging. To add middleware to an app, use the App::middleware method.

Hello, world!

You can start a simple Tide application that listens for GET requests at path /hello on 127.0.0.1:8000 with:


let mut app = tide::App::new();
app.at("/hello").get(|_| async move {"Hello, world!"});
app.serve("127.0.0.1:8000");

Routing and parameters

Tide's routing system is simple and similar to many other frameworks. It uses :foo for "wildcard" URL segments, and :foo* to match the rest of a URL (which may include multiple segments). Here's an example using wildcard segments as parameters to endpoints:


use tide::error::ResultExt;

async fn hello(cx: tide::Context<()>) -> tide::EndpointResult<String> {
    let user: String = cx.param("user").client_err()?;
    Ok(format!("Hello, {}!", user))
}

async fn goodbye(cx: tide::Context<()>) -> tide::EndpointResult<String> {
    let user: String = cx.param("user").client_err()?;
    Ok(format!("Goodbye, {}.", user))
}

let mut app = tide::App::new();

app.at("/hello/:user").get(hello);
app.at("/goodbye/:user").get(goodbye);
app.at("/").get(|_| async move {
    "Use /hello/{your name} or /goodbye/{your name}"
});

app.serve("127.0.0.1:8000");

You can learn more about routing in the App::at documentation.

Application state


use http::status::StatusCode;
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
use tide::{error::ResultExt, response, App, Context, EndpointResult};

#[derive(Default)]
struct Database {
    contents: Mutex<Vec<Message>>,
}

#[derive(Serialize, Deserialize, Clone)]
struct Message {
    author: Option<String>,
    contents: String,
}

impl Database {
    fn insert(&self, msg: Message) -> usize {
        let mut table = self.contents.lock().unwrap();
        table.push(msg);
        table.len() - 1
    }

    fn get(&self, id: usize) -> Option<Message> {
        self.contents.lock().unwrap().get(id).cloned()
    }
}

async fn new_message(mut cx: Context<Database>) -> EndpointResult<String> {
    let msg = cx.body_json().await.client_err()?;
    Ok(cx.state().insert(msg).to_string())
}

async fn get_message(cx: Context<Database>) -> EndpointResult {
    let id = cx.param("id").client_err()?;
    if let Some(msg) = cx.state().get(id) {
        Ok(response::json(msg))
    } else {
        Err(StatusCode::NOT_FOUND)?
    }
}

fn main() {
    let mut app = App::with_state(Database::default());
    app.at("/message").post(new_message);
    app.at("/message/:id").get(get_message);
    app.serve("127.0.0.1:8000").unwrap();
}

Methods

impl App<()>[src]

pub fn new() -> App<()>[src]

Create an empty App, with no initial middleware or configuration.

impl<State: Send + Sync + 'static> App<State>[src]

pub fn with_state(state: State) -> App<State>[src]

Create an App, with initial middleware or configuration.

pub fn at<'a>(&'a mut self, path: &'a str) -> Route<'a, State>[src]

Add a new route at the given path, relative to root.

Routing means mapping an HTTP request to an endpoint. Here Tide applies a "table of contents" approach, which makes it easy to see the overall app structure. Endpoints are selected solely by the path and HTTP method of a request: the path determines the resource and the HTTP verb the respective endpoint of the selected resource. Example:

app.at("/").get(|_| async move {"Hello, world!"});

A path is comprised of zero or many segments, i.e. non-empty strings separated by '/'. There are two kinds of segments: concrete and wildcard. A concrete segment is used to exactly match the respective part of the path of the incoming request. A wildcard segment on the other hand extracts and parses the respective part of the path of the incoming request to pass it along to the endpoint as an argument. A wildcard segment is written as :name, which creates an endpoint parameter called name. It is not possible to define wildcard segments with different names for otherwise identical paths.

Wildcard definitions can be followed by an optional wildcard modifier. Currently, there is only one modifier: *, which means that the wildcard will match to the end of given path, no matter how many segments are left, even nothing. It is an error to define two wildcard segments with different wildcard modifiers, or to write other path segment after a segment with wildcard modifier.

Here are some examples omitting the HTTP verb based endpoint selection:

app.at("/");
app.at("/hello");
app.at("add_two/:num");
app.at("static/:path*");

There is no fallback route matching, i.e. either a resource is a full match or not, which means that the order of adding resources has no effect.

pub fn middleware(&mut self, m: impl Middleware<State>) -> &mut Self[src]

Add middleware to an application.

Middleware provides application-global customization of the request/response cycle, such as compression, logging, or header modification. Middleware is invoked when processing a request, and can either continue processing (possibly modifying the response) or immediately return a response. See the Middleware trait for details.

Middleware can only be added at the "top level" of an application, and is processed in the order in which it is applied.

pub fn into_http_service(self) -> Server<State>[src]

Make this app into an HttpService.

This lower-level method lets you host a Tide application within an HTTP server of your choice, via the http_service interface crate.

pub fn serve(self, addr: impl ToSocketAddrs) -> Result<()>[src]

Start serving the app at the given address.

Blocks the calling thread indefinitely.

Trait Implementations

impl Default for App<()>[src]

Auto Trait Implementations

impl<State> Send for App<State> where
    State: Send

impl<State> Sync for App<State> where
    State: Sync

impl<State> Unpin for App<State> where
    State: Unpin

impl<State> !UnwindSafe for App<State>

impl<State> !RefUnwindSafe for App<State>

Blanket Implementations

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> From<T> for T[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]

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