[−][src]Struct tide::App
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:
#![feature(async_await)] 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:
#![feature(async_await, futures_api)] 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
#![feature(async_await, futures_api, await_macro)] use tide::{Context, EndpointResult, error::ResultExt, response, App}; use http::StatusCode; use std::sync::Mutex; #[derive(Default)] struct Database { contents: Mutex<Vec<Message>>, } impl Database { fn messages(&self) -> std::sync::MutexGuard<Vec<Message>> { self.contents.lock().unwrap() } } #[derive(Serialize, Deserialize, Clone)] struct Message { author: Option<String>, contents: String, } async fn new_message(cx: Context<Database>) -> EndpointResult<String> { let msg = await!(cx.body_json()).client_err()?; let mut messages = cx.app_data().messages(); let id = messages.len(); messages.push(msg); Ok(id.to_string()) } async fn get_message(cx: Context<Database>) -> EndpointResult { let id: usize = cx.param("id").client_err()?; if let Some(msg) = cx.app_data().messages().get(id) { Ok(response::json(msg)) } else { Err(StatusCode::NOT_FOUND)? } } fn main() { let mut app = App::new(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<AppData: Send + Sync + 'static> App<AppData>
[src]
pub fn new(data: AppData) -> App<AppData>
[src]
Create an empty App
, with no initial middleware or configuration.
pub fn at<'a>(&'a mut self, path: &'a str) -> Route<'a, AppData>
[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<AppData>) -> &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<AppData>
[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.
Auto Trait Implementations
impl<AppData> Send for App<AppData> where
AppData: Send,
AppData: Send,
impl<AppData> Sync for App<AppData> where
AppData: Sync,
AppData: Sync,
Blanket Implementations
impl<T> From for T
[src]
impl<T, U> Into for T where
U: From<T>,
[src]
U: From<T>,
impl<T, U> TryFrom for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<T> Borrow for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut for T where
T: ?Sized,
[src]
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,