[go: up one dir, main page]

tide/
lib.rs

1//! Tide is a minimal and pragmatic Rust web application framework built for
2//! rapid development. It comes with a robust set of features that make
3//! building async web applications and APIs easier and more fun.
4//!
5//! # Getting started
6//!
7//! In order to build a web app in Rust you need an HTTP server, and an async
8//! runtime. After running `cargo init` add the following lines to your
9//! `Cargo.toml` file:
10//!
11//! ```toml
12//! # Example, use the version numbers you need
13//! tide = "0.14.0"
14//! async-std = { version = "1.6.0", features = ["attributes"] }
15//! serde = { version = "1.0", features = ["derive"] }
16//!```
17//!
18//! # Examples
19//!
20//! Create an HTTP server that receives a JSON body, validates it, and responds with a
21//! confirmation message.
22//!
23//! ```no_run
24//! use tide::Request;
25//! use tide::prelude::*;
26//!
27//! #[derive(Debug, Deserialize)]
28//! struct Animal {
29//!     name: String,
30//!     legs: u8,
31//! }
32//!
33//! #[async_std::main]
34//! async fn main() -> tide::Result<()> {
35//!     let mut app = tide::new();
36//!     app.at("/orders/shoes").post(order_shoes);
37//!     app.listen("127.0.0.1:8080").await?;
38//!     Ok(())
39//! }
40//!
41//! async fn order_shoes(mut req: Request<()>) -> tide::Result {
42//!     let Animal { name, legs } = req.body_json().await?;
43//!     Ok(format!("Hello, {}! I've put in an order for {} shoes", name, legs).into())
44//! }
45//! ````
46//!
47//! ```sh
48//! $ curl localhost:8080/orders/shoes -d '{ "name": "Chashu", "legs": 4 }'
49//! Hello, Chashu! I've put in an order for 4 shoes
50//!
51//! $ curl localhost:8080/orders/shoes -d '{ "name": "Mary Millipede", "legs": 750 }'
52//! number too large to fit in target type
53//! ```
54//! See more examples in the [examples](https://github.com/http-rs/tide/tree/main/examples) directory.
55
56#![cfg_attr(feature = "docs", feature(doc_cfg))]
57#![forbid(unsafe_code)]
58#![deny(missing_debug_implementations, nonstandard_style)]
59#![warn(missing_docs, unreachable_pub, future_incompatible, rust_2018_idioms)]
60#![doc(test(attr(deny(warnings))))]
61#![doc(test(attr(allow(unused_extern_crates, unused_variables))))]
62#![doc(html_favicon_url = "https://yoshuawuyts.com/assets/http-rs/favicon.ico")]
63#![doc(html_logo_url = "https://yoshuawuyts.com/assets/http-rs/logo-rounded.png")]
64
65#[cfg(feature = "cookies")]
66mod cookies;
67mod endpoint;
68mod fs;
69mod middleware;
70mod redirect;
71mod request;
72mod response;
73mod response_builder;
74mod route;
75mod router;
76mod server;
77
78pub mod convert;
79pub mod listener;
80pub mod log;
81pub mod prelude;
82pub mod security;
83pub mod sse;
84pub mod utils;
85
86#[cfg(feature = "sessions")]
87pub mod sessions;
88
89pub use endpoint::Endpoint;
90pub use middleware::{Middleware, Next};
91pub use redirect::Redirect;
92pub use request::Request;
93pub use response::Response;
94pub use response_builder::ResponseBuilder;
95pub use route::Route;
96pub use server::Server;
97
98pub use http_types::{self as http, Body, Error, Status, StatusCode};
99
100/// Create a new Tide server.
101///
102/// # Examples
103///
104/// ```no_run
105/// # use async_std::task::block_on;
106/// # fn main() -> Result<(), std::io::Error> { block_on(async {
107/// #
108/// let mut app = tide::new();
109/// app.at("/").get(|_| async { Ok("Hello, world!") });
110/// app.listen("127.0.0.1:8080").await?;
111/// #
112/// # Ok(()) }) }
113/// ```
114#[must_use]
115pub fn new() -> server::Server<()> {
116    Server::new()
117}
118
119/// Create a new Tide server with shared application scoped state.
120///
121/// Application scoped state is useful for storing items
122///
123/// # Examples
124///
125/// ```no_run
126/// # use async_std::task::block_on;
127/// # fn main() -> Result<(), std::io::Error> { block_on(async {
128/// #
129/// use tide::Request;
130///
131/// /// The shared application state.
132/// #[derive(Clone)]
133/// struct State {
134///     name: String,
135/// }
136///
137/// // Define a new instance of the state.
138/// let state = State {
139///     name: "Nori".to_string()
140/// };
141///
142/// // Initialize the application with state.
143/// let mut app = tide::with_state(state);
144/// app.at("/").get(|req: Request<State>| async move {
145///     Ok(format!("Hello, {}!", &req.state().name))
146/// });
147/// app.listen("127.0.0.1:8080").await?;
148/// #
149/// # Ok(()) }) }
150/// ```
151pub fn with_state<State>(state: State) -> server::Server<State>
152where
153    State: Clone + Send + Sync + 'static,
154{
155    Server::with_state(state)
156}
157
158/// A specialized Result type for Tide.
159pub type Result<T = Response> = std::result::Result<T, Error>;